How to remove all white spaces in java [duplicate] Ask Question

How to remove all white spaces in java [duplicate] Ask Question

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.

このプログラムで私がやろうとしていたことは、スペースが見つかるまで各文字を分析し、その部分文字列を最初のトークンとして保存することです。その後、トークンがなくなるか行末に達するまで再度ループします。

コンパイルしようとすると、次のようなエラーが繰り返し表示されます。

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 ;
           }
         }
        }
}

もっと簡単な方法があればありがたいのですが、それでもこのプログラムを動作させたいと思っています。

入力にセンチネルを使用することはできません。


皆さんのご協力に感謝します。

より簡単な方法を使用し、Javadoc を読みます。

ベストアンサー1

java.lang.Stringクラスにメソッドがありsubstringませんsubstr。これがプログラムのエラーです。

さらに、正規表現を使用しても問題ない場合は、これを 1 行で実行できます。

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

おすすめ記事