目次
文字列を分割する – split
特定の文字列(デリミタ)で文字列を分割します。
サンプルコード
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!
文字列をデリミタで結合する – join
特定の文字列(デリミタ)で文字列を結合します(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); //結果は同じ
}
出力結果:
りんご,みかん,バナナ
指定範囲の文字列を切り出す – substring
切り出しの始点と終点を指定して、文字列を一部切り出します。
サンプルコード
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!
前後の空白を削除する – trim
文字列の前後の半角スペース、改行、タブを除去します。
文字列の途中にある空白や全角スペースは除去されません。
サンプルコード
public static void trimSample() {
String str = " hello world! ";
System.out.println(str.trim());
}
出力結果:
hello world!
文字列の一部を別の文字列で置き換える – replace
文字列の一部を指定した文字列で置き換えます。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!
文字列の文字数を返す – length
文字列の文字数を返します。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
