「Java」trim関数で先頭と末尾の半角空白を取り除く

環境
Eclipse 2019
jdk1.8

書式
public String trim()
文字列の先頭と末尾の半角空白を取り除きます。
空白が複数の場合、複数の空白を取り除きます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.stud;
public class TestDemo {
public static void main(String[] args) {
// 半角空白
String strA = " テスト+3 ";
String strB = strA.trim();
String strC = " テスト+3 ";
System.out.println("半角空白を取り除く前: " + strA.length());
System.out.println(strB);
System.out.println("半角空白を取り除く後: " + strB.length());
System.out.println(strC);
}
}
package com.arkgame.stud; public class TestDemo { public static void main(String[] args) { // 半角空白 String strA = " テスト+3 "; String strB = strA.trim(); String strC = " テスト+3 "; System.out.println("半角空白を取り除く前: " + strA.length()); System.out.println(strB); System.out.println("半角空白を取り除く後: " + strB.length()); System.out.println(strC); } }
package com.arkgame.stud;

public class TestDemo {

      public static void main(String[] args) {
            // 半角空白
            String strA = " テスト+3  ";
            String strB = strA.trim();
            String strC = "  テスト+3  ";

            System.out.println("半角空白を取り除く前: " + strA.length());
            System.out.println(strB);
            System.out.println("半角空白を取り除く後: " + strB.length());

            System.out.println(strC);
      }

}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
半角空白を取り除く前: 8
テスト+3
半角空白を取り除く後: 5
テスト+3
半角空白を取り除く前: 8 テスト+3 半角空白を取り除く後: 5 テスト+3
半角空白を取り除く前: 8
テスト+3
半角空白を取り除く後: 5
  テスト+3

 

Java

Posted by arkgame