LoginSignup
0
0

More than 3 years have passed since last update.

【Java】文字列最後の空白を消したい

Posted at

配列の要素を文字列連結して出力。
その際、要素と要素の間にスペースを入れたいが、末尾に空白が残ってしまう。


    public static void main(String[] args) {

        String arr[] = {"orange","apple","cherry","melon","grape"};

        String ret = "";

        for (int i = 0; i < arr.length; i++) {
            ret += arr[i] + " ";

        }
        System.out.println("【" + ret + "】");
    }//出力結果【orange apple cherry melon grape 】

メソッドtrim()を使って空白を削除

System.out.println("【" + ret.trim() + "】");
//出力結果【orange apple cherry melon grape】

trim()は頭と末尾の空白を削除した文字列を返します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0