Java で文字列操作する関数・メソッドの一覧
String
先頭・末尾の文字列検索 (startsWith, endsWith)
String str = "abcdef";
System.out.println(str.startsWith("abc")); // => true
System.out.println(str.endsWith("ghi")); // => false
指定文字列で連結 (String.join)
String[] elements = {"abc", "def", "ghi"};
System.out.println(String.join(",", elements)); // => abc,def,ghi
前後の空白を削除 (trim)
String str = " abc\n\t ";
System.out.println(str.trim()); // => abc
部分文字列 (substring)
String input = "abcdefghi";
System.out.println(input.substring(5,7)); // => fg
文字列の検索 (indexOf)
String input = "abcdefghi";
System.out.println(input.indexOf("def")); // => 3
System.out.println(input.indexOf("jkl")); // => -1
文字列の置換 (replace, replaceAll, replaceFirst)
正規表現が入力可能
String input = "abc, def, ghi";
System.out.println(input.replaceAll(",\s*", ";"));
// => abc;def;ghi
文字列の分割 (split)
正規表現が入力可能
String input = "abc, def, ghi,123";
String[] res = input.split(",\s*");
for (String str : res) {
System.out.println(str);
}
// => abc
// => def
// => ghi
// => 123
文字列の比較 (equals, compareTo)
String input1 = "AAA";
String input2 = "BBB";
System.out.println(input1.equals(input2)); // => false
System.out.println(input1.compareTo(input2)); // => -1
String input3 = "AAA";
System.out.println(input1.equals(input3)); // => true
System.out.println(input1.compareTo(input3)); // => 0
文字列バッファ (StringBuilder)
StringBuilder sb = new StringBuilder();
sb.append("hello, ");
sb.append("world!");
System.out.println(sb); // => hello, world!
エンコーディング
String str = "こんにちは";
try {
byte[] bytes = str.getBytes("SJIS");
System.out.println(Arrays.toString(bytes));
// => [-126, -79, -126, -15, -126, -55, -126, -65, -126, -51]
String newstr = new String(bytes, "SJIS");
System.out.println(newstr);
// => こんにちは
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
正規表現で完全マッチ判定
String pattern = "\\d{3}-\\d{4}";
System.out.println("123-4321".matches(pattern)); // => true
System.out.println("345-67890".matches(pattern)); // => false
正規表現で検索とグルーピング
String input = "038-123-4567";
Pattern pattern = Pattern.compile("(\\d{3})-(\\d{3})-(\\d{4})");
Matcher m = pattern.matcher(input);
if (m.find()) {
System.out.println(m.group(1)); // => 038
System.out.println(m.group(2)); // => 123
System.out.println(m.group(3)); // => 4567
}
正規表現で置換
String input = "<1>2<3>4";
System.out.println(input.replaceAll("<(\\d)>", "{$1}")); // => {1}2{3}4