如何删除java中的所有空格 [英] How to remove all white spaces in java

查看:247
本文介绍了如何删除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)

这是代码

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.

感谢大家的帮助,

我将使用更简单的方法,并将阅读javadoc。

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

推荐答案

java.lang.String class has method substring 不是 substr ,这就是程序中的错误。

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+","");

这篇关于如何删除java中的所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆