1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaのStringのよく使うメソッド集 — substring/split/replaceの罠

1
Posted at

JavaのStringのよく使うメソッド集 — substring/split/replaceの罠

はじめに

Javaの String はよく使うクラスですが、知らないとハマる落とし穴がいくつかあります。

この記事では「よく使うのに罠がある」メソッドを中心に整理します。


1. substring() — インデックスは「前まで」

String s = "Hello, Java";
//          0123456789...

System.out.println(s.substring(7));     // "Java"(7文字目から末尾まで)
System.out.println(s.substring(0, 5)); // "Hello"(0〜4文字目)

罠: 第2引数は「その文字を含まない」終端インデックスです。

// "Hello"を取りたいのに
System.out.println(s.substring(0, 5)); // "Hello"  ← 正解
System.out.println(s.substring(0, 6)); // "Hello," ← 1個多い

覚え方: substring(from, to)[from, to) の半開区間。


2. split() — 引数は正規表現

最もハマりやすい罠です。

String s = "a.b.c";
String[] parts = s.split(".");  // 直感的に ["a", "b", "c"] を期待
System.out.println(parts.length); // → 0(!!)

split() の引数は正規表現です。. は「任意の1文字」を表すワイルドカードなので、全文字がセパレータになってしまいます。

// 正しい書き方:ドットをエスケープする
String[] parts = s.split("\\.");
System.out.println(Arrays.toString(parts)); // [a, b, c]

同様に注意が必要な文字:|, *, +, ?, (, ), [, {

// パイプで分割する場合もエスケープが必要
"a|b|c".split("\\|"); // OK
"a|b|c".split("|");   // NG(全文字が分割される)

3. replace() と replaceAll() の違い

String s = "a.b.c";

s.replace(".", "/");      // → "a/b/c"(文字列をそのまま検索)
s.replaceAll("\\.", "/"); // → "a/b/c"(正規表現で検索)
s.replaceAll(".", "/");   // → "///// "(全文字が置換される!)
メソッド 第1引数の扱い
replace(old, new) 文字列そのまま
replaceAll(regex, new) 正規表現
replaceFirst(regex, new) 正規表現(最初の1つだけ)

指針: 単純な文字列置換なら replace() を使う。正規表現が必要な時だけ replaceAll()


4. isEmpty() と isBlank() の違い

String empty = "";
String blank = "   "; // スペースのみ

empty.isEmpty(); // true
blank.isEmpty(); // false ← スペースは空じゃない

empty.isBlank(); // true(Java 11以降)
blank.isBlank(); // true ← スペースのみも空とみなす

使い分け:

  • 空文字だけ弾きたい → isEmpty()
  • スペースだけの入力も弾きたい → isBlank()(バリデーションには通常こちら)

5. trim() と strip() の違い

String s = "  hello  ";

s.trim();  // "hello"(ASCIIの半角スペースのみ除去)
s.strip(); // "hello"(Unicode空白も除去、Java 11以降推奨)

全角スペースへの対応:

String s = " hello "; // 全角スペース

s.trim();        // " hello "(全角スペースは除去されない!)
s.strip();       // "hello"(全角スペースも除去される)
s.stripLeading(); // "hello "(先頭のみ)
s.stripTrailing(); // " hello"(末尾のみ)

Java 11以降では strip() を使うのが推奨です。


6. contains() / startsWith() / endsWith()

String s = "Hello, Java World";

s.contains("Java");      // true
s.startsWith("Hello");   // true
s.endsWith("World");     // true
s.startsWith("Java", 7); // true(7文字目から確認)

これらは正規表現ではなく文字列をそのまま検索するので安全です。


7. formatted() — String.format() の新しい書き方

// 旧来の書き方
String msg = String.format("名前: %s、年齢: %d", "田中", 25);

// Java 15以降:インスタンスメソッドとして書ける
String msg = "名前: %s、年齢: %d".formatted("田中", 25);

テキストブロックと組み合わせると特に便利です:

String html = """
        <p>名前: %s</p>
        <p>年齢: %d</p>
        """.formatted("田中", 25);

まとめ

メソッド 罠・注意点
substring(from, to) to は含まない(半開区間)
split(regex) 引数は正規表現。. は要エスケープ
replace() vs replaceAll() replaceAllは正規表現。単純置換はreplace()
isEmpty() vs isBlank() スペースのみの文字列はisBlank()で検出
trim() vs strip() 全角スペース対応はstrip()(Java 11+)
formatted() String.format()のインスタンス版(Java 15+)

Stringは毎日使うクラスだからこそ、罠を先に知っておくと実務で助かります。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?