java 删除空格,如何删除java中的所有空格

I have a programming assignment and part of it requires me to make code that reads a line from the user and removes all the white space within that line.

the line can consist of one word or more.

What I was trying to do with this program is have it analyze each character until it finds a space and then save that substring as the first token. then loop again until it reaches no more tokens or the end of the line.

I keep on getting this when I try to compile it:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

at java.lang.String.charAt(String.java:694)

at trim.main(trim.java:23)

Here is the code

import java.util.Scanner ;

import java.lang.Character;

import java.lang.String ;

public class trim

{

public static void main (String[]args)

{

String a ;

String b ;

String c ;

char aChar ;

int i = 0 ;

Scanner scan = new Scanner(System.in);

a = scan.nextLine();

a =a.trim() ;

for ( ; i >= 0 ; i++ )

{

aChar = a.charAt(i) ;

if (aChar != 32)

{

a = a.substring(0,i+1);

}

else

{

b = a.substring(i,160) ;

b= b.trim();

c = c + a ;

c = c.trim() ;

a = b ;

i = 0 ;

}

if (b.equals(null))

{

i = -1 ;

}

}

}

}

easier ways to do this is appreciated, but I still want to get this program working.

and I can't use sentinels in the input.

Thanks everybody for all the help,

I will use the simpler method , and will read the javadoc.

解决方案

java.lang.String class has method substring not substr , thats the error in your program.

Moreover you can do this in one single line if you are ok in using regular expression.

a.replaceAll("\\s+","");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值