2019年11月2日
public static void splitSample() { String line = "りんご,みかん,バナナ"; String[] fruits = line.split(","); for (String fruit : fruits) { System.out.println(fruit); } }出力結果:
りんご みかん ばなな
public static void plusSample() { String s1 = "hello "; String s2 = "world!"; System.out.println(s1 + s2); }出力結果:
hello world!
特定の文字列(デリミタ)で文字列を結合します(java8以降で利用可能)
public static void joinSample() { String line = String.join(",", "りんご", "みかん", "バナナ"); System.out.println(line); }
join は文字列配列でも同じように結合できます。
public static void joinArraySample() { String[] fruits = {"りんご", "みかん", "バナナ"}; String line = String.join(",", fruits); System.out.println(line); //結果は同じ }出力結果:
りんご,みかん,バナナ
public static void substringSample() { String str = "hello world!"; System.out.println(str.substring(0, 5)); System.out.println(str.substring(2, 9)); System.out.println(str.substring(6)); //始点だけ指定することもできる }出力結果:
hello llo wor world!
public static void trimSample() { String str = " hello world! "; System.out.println(str.trim()); }出力結果:
hello world!
文字列の一部を指定した文字列で置き換えます。replaceは全ての一致した文字列を置き換えます。
public static void replaceSample() { String str = "hello world!"; System.out.println(str.replace("l", "×")); }出力結果:
he××o wor×d!
replaceFirstは最初に一致した文字列のみを置き換えます。
public static void replaceFirstSample() { String str = "hello world!"; System.out.println(str.replaceFirst("l", "×")); }出力結果:
he×lo world!
文字列の文字数を返します。String.length()は単純に文字数を返します。
public static void lengthSample() { String str = "〇〇県□□市△△町10-11"; System.out.println(str.length()); }出力結果:
14
バイト数が知りたい場合はString.getBytes().lengthを使用します。Java8から文字コードは標準でUTF8なので、全角文字1文字あたり3バイトです。
public static void byteLengthSample() { String str = "〇〇県□□市△△町10-11"; System.out.println(str.getBytes().length); }出力結果:
32