広告

Java : String (文字列) - API使用例

String (Java SE 20 & JDK 20) の使用例まとめです。
文字列操作のメソッドがいろいろとそろっています。
API仕様のおともにどうぞ。


概要

Stringクラスは文字列を表します。 Javaプログラム内の"abc"などのリテラル文字列はすべて、このクラスのインスタンスとして実行されます。

クラス構成

String は文字列を表現するクラスです。
文字列の生成には、通常は String のコンストラクタは使わずにリテラル表記を使います。

final var s = "abcde";
System.out.println(s); // "abcde"

// 大文字に変換。
final var upper = s.toUpperCase();
System.out.println(upper); // "ABCDE"

文字列に関しては以下の記事も参考にしていただけたら幸いです。

サロゲート文字について

文字列を構成する文字は、基本的には char 型で表現できます。

final char c1 = 'a';
final char c2 = 'あ';

char のサイズは 2バイトです。
しかし、そのサイズにおさまらない文字が存在します。

例えば、"𩸽" という文字です。

final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"
System.out.println(surrogate.length()); // 2

final var chars = surrogate.chars().toArray();
System.out.println(Arrays.toString(chars)); // [55399, 56893]

文字自体は1文字ですが、lengthchars では 2文字として結果が返ります。
このような問題があるため、Javaでは int 型を使ったコードポイントが追加されました。

int は 4バイトあるので、すべての文字がおさまります。

final var surrogate = "\uD867\uDE3D";
System.out.println(surrogate); // "𩸽"

final var codePoints = surrogate.codePoints().toArray();
System.out.println(Arrays.toString(codePoints)); // [171581]

Stringクラスにも、上記の codePoints のように、文字を int で扱う API がいろいろと追加されています。
基本的には char のAPIは使わずに、int のコードポイント API を使うことをおすすめします。


フィールド

static final Comparator<String> CASE_INSENSITIVE_ORDER

compareToIgnoreCaseと同様にStringオブジェクトを順序付けするComparator。

final var list = new ArrayList<String>();
list.add("Tree");
list.add("book");
list.add("stone");
list.add("Cake");

System.out.println(list); // [Tree, book, stone, Cake]

list.sort(Comparator.naturalOrder());
System.out.println(list); // [Cake, Tree, book, stone]

list.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(list); // [book, Cake, stone, Tree]
final var list = new ArrayList<String>();
list.add("D");
list.add("c");
list.add("B");
list.add("a");

System.out.println(list); // [D, c, B, a]

list.sort(Comparator.naturalOrder());
System.out.println(list); // [B, D, a, c]

list.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(list); // [a, B, c, D]

コンストラクタ

String ()

新しく生成されたStringオブジェクトを初期化して、空の文字シーケンスを表すようにします。

API仕様に、このコンストラクタを使う必要はありません、とあるので代わりにリテラル表記を使いましょう。

// おすすめ
final var s = "";
System.out.println(s); // ""
System.out.println(s.isEmpty()); // true
// 間違いではありませんが、あまりおすすめしません。
final var s = new String();
System.out.println(s); // ""
System.out.println(s.isEmpty()); // true

String (byte[] bytes)

default charsetを使用して指定したバイト配列をデコードすることによって、新しいStringを作成します。

final var bytes = "abcde".getBytes();
System.out.println(Arrays.toString(bytes)); // [97, 98, 99, 100, 101]

final var s = new String(bytes);
System.out.println(s); // "abcde"
System.out.println(Charset.defaultCharset()); // UTF-8

final var sjis = "あいうえお".getBytes("Shift_JIS");

// [-126, -96, -126, -94, -126, -92, -126, -90, -126, -88]
System.out.println(Arrays.toString(sjis));
System.out.println(new String(sjis)); // "����������" ←文字化け

final var utf8 = "あいうえお".getBytes(StandardCharsets.UTF_8);

// [-29, -127, -126, -29, -127, -124, -29, -127, -122, -29, -127, -120, -29, -127, -118]
System.out.println(Arrays.toString(utf8));
System.out.println(new String(utf8)); // "あいうえお"

String (byte[] ascii, int hibyte)

非推奨。 このメソッドでは、バイトから文字への変換が正しく行われません。

非推奨です。

String (byte[] bytes, int offset, int length)

default charsetを使用して、指定したバイトのサブ配列をデコードすることによって、新しいStringを構成します。

final var bytes = "abcd".getBytes();
System.out.println(Arrays.toString(bytes)); // [97, 98, 99, 100]

System.out.println(new String(bytes, 0, 0)); // ""
System.out.println(new String(bytes, 0, 1)); // "a"
System.out.println(new String(bytes, 0, 2)); // "ab"
System.out.println(new String(bytes, 0, 3)); // "abc"
System.out.println(new String(bytes, 0, 4)); // "abcd"

System.out.println(new String(bytes, 1, 3)); // "bcd"
System.out.println(new String(bytes, 2, 2)); // "cd"
System.out.println(new String(bytes, 3, 1)); // "d"
System.out.println(new String(bytes, 4, 0)); // ""
System.out.println(Charset.defaultCharset()); // UTF-8

final var bytes = "あいうえお".getBytes();

// [-29, -127, -126, -29, -127, -124, -29, -127, -122, -29, -127, -120, -29, -127, -118]
System.out.println(Arrays.toString(bytes));

final var s = new String(bytes, 3, 9);
System.out.println(s); // "いうえ"

String (byte[] ascii, int hibyte, int offset, int count)

非推奨。 このメソッドでは、バイトから文字への変換が正しく行われません。

非推奨です。

String (byte[] bytes, int offset, int length, String charsetName)

指定された文字セットを使用して、指定されたバイト部分配列をデコードすることによって、新しいStringを構築します。

下記のメソッドを組み合わせた挙動となります。
それぞれのコード例をご確認ください。

String (byte[] bytes, int offset, int length, Charset charset)

指定された文字セットを使用して、指定された部分バイト配列を復号化することにより、新しいStringを構築します。

下記のメソッドを組み合わせた挙動となります。
それぞれのコード例をご確認ください。

String (byte[] bytes, String charsetName)

指定された文字セットを使用して、指定されたバイト配列をデコードすることにより、新しいStringを構築します。

final var bytes = "abcd".getBytes("UTF-8");
System.out.println(Arrays.toString(bytes)); // [97, 98, 99, 100]

System.out.println(new String(bytes, "UTF-8")); // "abcd"
final var sjis = "あいうえお".getBytes("Shift_JIS");

// [-126, -96, -126, -94, -126, -92, -126, -90, -126, -88]
System.out.println(Arrays.toString(sjis));
System.out.println(new String(sjis, "Shift_JIS")); // "あいうえお"

final var utf8 = "あいうえお".getBytes("UTF-8");

// [-29, -127, -126, -29, -127, -124, -29, -127, -122, -29, -127, -120, -29, -127, -118]
System.out.println(Arrays.toString(utf8));
System.out.println(new String(utf8, "UTF-8")); // "あいうえお"

String (byte[] bytes, Charset charset)

指定された文字セットを使用して、指定されたバイト配列をデコードすることにより、新しいStringを構築します。

final var bytes = "abcd".getBytes(StandardCharsets.UTF_8);
System.out.println(Arrays.toString(bytes)); // [97, 98, 99, 100]

System.out.println(new String(bytes, StandardCharsets.UTF_8)); // "abcd"
final var sjis = "あいうえお".getBytes(Charset.forName("Shift_JIS"));

// [-126, -96, -126, -94, -126, -92, -126, -90, -126, -88]
System.out.println(Arrays.toString(sjis));
System.out.println(new String(sjis, Charset.forName("Shift_JIS"))); // "あいうえお"

final var utf8 = "あいうえお".getBytes(StandardCharsets.UTF_8);

// [-29, -127, -126, -29, -127, -124, -29, -127, -122, -29, -127, -120, -29, -127, -118]
System.out.println(Arrays.toString(utf8));
System.out.println(new String(utf8, StandardCharsets.UTF_8)); // "あいうえお"

String (char[] value)

新しいStringを割り当てて、これが文字配列引数に現在含まれている文字シーケンスを表すようにします。

final char[] value = {'a', 'b', 'c', 'd'};
System.out.println(Arrays.toString(value)); // [a, b, c, d]

final var s = new String(value);
System.out.println(s); // "abcd"
final char[] value = {'あ', 'い', 'う', 'え', 'お'};
System.out.println(Arrays.toString(value)); // [あ, い, う, え, お]

final var s = new String(value);
System.out.println(s); // "あいうえお"

String (char[] value, int offset, int count)

文字配列引数の部分配列からなる文字を含む新しいStringを割り当てます。

final char[] value = {'a', 'b', 'c', 'd'};
System.out.println(Arrays.toString(value)); // [a, b, c, d]

System.out.println(new String(value, 0, 0)); // ""
System.out.println(new String(value, 0, 1)); // "a"
System.out.println(new String(value, 0, 2)); // "ab"
System.out.println(new String(value, 0, 3)); // "abc"
System.out.println(new String(value, 0, 4)); // "abcd"

System.out.println(new String(value, 1, 3)); // "bcd"
System.out.println(new String(value, 2, 2)); // "cd"
System.out.println(new String(value, 3, 1)); // "d"
System.out.println(new String(value, 4, 0)); // ""
final char[] value = {'あ', 'い', 'う', 'え', 'お'};
System.out.println(Arrays.toString(value)); // [あ, い, う, え, お]

final var s = new String(value, 2, 3);
System.out.println(s); // "うえお"

String (int[] codePoints, int offset, int count)

Unicodeコード・ポイント配列引数の部分配列からなる文字を含む新しいStringを割り当てます。

final var codePoints = "abcd".codePoints().toArray();
System.out.println(Arrays.toString(codePoints)); // [97, 98, 99, 100]

System.out.println(new String(codePoints, 0, 0)); // ""
System.out.println(new String(codePoints, 0, 1)); // "a"
System.out.println(new String(codePoints, 0, 2)); // "ab"
System.out.println(new String(codePoints, 0, 3)); // "abc"
System.out.println(new String(codePoints, 0, 4)); // "abcd"

System.out.println(new String(codePoints, 1, 3)); // "bcd"
System.out.println(new String(codePoints, 2, 2)); // "cd"
System.out.println(new String(codePoints, 3, 1)); // "d"
System.out.println(new String(codePoints, 4, 0)); // ""
final var codePoints = "あいうえお".codePoints().toArray();
System.out.println(Arrays.toString(codePoints)); // [12354, 12356, 12358, 12360, 12362]

final var s = new String(codePoints, 1, 3);
System.out.println(s); // "いうえ"

String (String original)

新しく生成されたStringオブジェクトを初期化して、引数と同じ文字シーケンスを表すようにします。つまり、新しく作成された文字列は引数文字列のコピーになります。

API仕様に、このコンストラクタを使う必要はありません、とあるので代わりにリテラル表記を使いましょう。

// おすすめ
final var s = "abcd";
System.out.println(s); // "abcd"
// 間違いではありませんが、あまりおすすめしません。
final var s = new String("abcd");
System.out.println(s); // "abcd"

String (StringBuffer buffer)

文字列バッファ引数に現在含まれている文字列を持つ新しい文字列を構築します。

final var buffer = new StringBuffer();
buffer.append("num : ");
buffer.append(123);

final var s = new String(buffer);
System.out.println(s); // "num : 123"

String (StringBuilder builder)

文字列ビルダー引数に現在含まれている文字列を持つ新しい文字列を割り当てます。

final var builder = new StringBuilder();
builder.append("num : ");
builder.append(123);

final var s = new String(builder);
System.out.println(s); // "num : 123"

メソッド

char charAt (int index)

指定されたインデックスのchar値を返します。

final var s1 = "abc";
//s1.charAt(-1); // IndexOutOfBoundsException
System.out.println(s1.charAt(0)); // a
System.out.println(s1.charAt(1)); // b
System.out.println(s1.charAt(2)); // c
//s1.charAt(3); // IndexOutOfBoundsException

final var s2 = "あいうえお";
System.out.println(s2.charAt(1)); // い
System.out.println(s2.charAt(4)); // お
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D"; // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = surrogate + "ab";
System.out.println(s); // "𩸽ab"

final var ret1 = s.charAt(0);
System.out.println(ret1); // ? <- 文字化け
System.out.println(Integer.toHexString(ret1)); // d867 <- サロゲート値

final var ret2 = s.charAt(1);
System.out.println(ret2); // ? <- 文字化け
System.out.println(Integer.toHexString(ret2)); // de3d <- サロゲート値

final var ret3 = s.charAt(2);
System.out.println(ret3); // a

final var ret4 = s.charAt(3);
System.out.println(ret4); // b

//s.charAt(4); // IndexOutOfBoundsException

IntStream chars ()

このシーケンスのchar値をゼロ拡張したintを含むストリームを返します。

サロゲート・コード・ポイントは1文字としては解釈されないので注意。
もし1文字として解釈したい場合は、codePoints を代わりにご使用ください。

// Unicodeで 0x61 = a, 0x62 = b, 0x63 = c, 0x64 = d, 0x65 = e
final var ret1 = "abcde".chars();

// [61, 62, 63, 64, 65]
System.out.println(ret1.mapToObj(Integer::toHexString).toList());

// Unicodeで 0x304b = か, 0x304d = き, 0x304f = く, 0x3051 = け, 0x3053 = こ
final var ret2 = "かきくけこ".chars();

// [304b, 304d, 304f, 3051, 3053]
System.out.println(ret2.mapToObj(Integer::toHexString).toList());
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D"; // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "ab" + surrogate;
System.out.println(s); // "ab𩸽"

final var ret = s.chars();

ret.forEach(c -> {
    System.out.println("%x : %c".formatted(c, c));
});

// 結果
// ↓
// "61 : a"
// "62 : b"
// "d867 : ?" <- 文字化け
// "de3d : ?" <- 文字化け

int codePointAt (int index)

指定されたインデックス位置の文字(Unicodeコード・ポイント)を返します。

final var s1 = "abc";
//s1.codePointAt(-1); // IndexOutOfBoundsException
System.out.println("%c".formatted(s1.codePointAt(0))); // a
System.out.println("%c".formatted(s1.codePointAt(1))); // b
System.out.println("%c".formatted(s1.codePointAt(2))); // c
//s1.codePointAt(3); // IndexOutOfBoundsException

final var s2 = "あいうえお";
System.out.println("%c".formatted(s2.codePointAt(1))); // い
System.out.println("%c".formatted(s2.codePointAt(4))); // お
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D"; // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = surrogate + "ab";
System.out.println(s); // "𩸽ab"

final var ret1 = s.codePointAt(0);
System.out.println("%c".formatted(ret1)); // 𩸽
System.out.println(Integer.toHexString(ret1)); // 29e3d

final var ret2 = s.codePointAt(1);
System.out.println("%c".formatted(ret2)); // ? <- 文字化け
System.out.println(Integer.toHexString(ret2)); // de3d <- サロゲート値

final var ret3 = s.codePointAt(2);
System.out.println("%c".formatted(ret3)); // a

final var ret4 = s.codePointAt(3);
System.out.println("%c".formatted(ret4)); // b

//s.codePointAt(4); // IndexOutOfBoundsException

int codePointBefore (int index)

指定されたインデックスの前の文字(Unicodeコード・ポイント)を返します。

final var s = "abc";

//s.codePointBefore(0); // IndexOutOfBoundsException
System.out.println("%c".formatted(s.codePointBefore(1)));  // a
System.out.println("%c".formatted(s.codePointBefore(2)));  // b
System.out.println("%c".formatted(s.codePointBefore(3)));  // c
//s.codePointBefore(4); // IndexOutOfBoundsException
final var s = "あいう";

//s.codePointBefore(0); // IndexOutOfBoundsException
System.out.println("%c".formatted(s.codePointBefore(1)));  // あ
System.out.println("%c".formatted(s.codePointBefore(2)));  // い
System.out.println("%c".formatted(s.codePointBefore(3)));  // う
//s.codePointBefore(4); // IndexOutOfBoundsException
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = surrogate + "ab";
System.out.println(s); // "𩸽ab"

//s.codePointBefore(0); // IndexOutOfBoundsException

final var ret1 = s.codePointBefore(1);
System.out.println("%c".formatted(ret1)); // ? <- 文字化け
System.out.println(Integer.toHexString(ret1)); // d867

final var ret2 = s.codePointBefore(2);
System.out.println("%c".formatted(ret2)); // 𩸽
System.out.println(Integer.toHexString(ret2)); // 29e3d

final var ret3 = s.codePointBefore(3);
System.out.println("%c".formatted(ret3)); // a

final var ret4 = s.codePointBefore(4);
System.out.println("%c".formatted(ret4)); // b

//s.codePointBefore(5); // IndexOutOfBoundsException

int codePointCount (int beginIndex, int endIndex)

このStringの指定されたテキスト範囲のUnicodeコード・ポイントの数を返します。

final var s1 = "abc";
System.out.println(s1.codePointCount(0, 3));  // 3
System.out.println(s1.codePointCount(1, 2));  // 1
//s1.codePointCount(-1, 3);  // IndexOutOfBoundsException
//s1.codePointCount(0, 4);  // IndexOutOfBoundsException

final var s2 = "かきく";
System.out.println(s2.codePointCount(0, 3));  // 3
System.out.println(s2.codePointCount(1, 2));  // 1
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = surrogate + "ab";
System.out.println(s); // "𩸽ab"

System.out.println(s.codePointCount(0, 1));  // 1
System.out.println(s.codePointCount(0, 2));  // 1
System.out.println(s.codePointCount(0, 3));  // 2
System.out.println(s.codePointCount(0, 4));  // 3
//s.codePointCount(0, 5);  // IndexOutOfBoundsException

IntStream codePoints ()

このシーケンスからコード・ポイント値のストリームを返します。

// Unicodeで 0x61 = a, 0x62 = b, 0x63 = c, 0x64 = d, 0x65 = e
final var ret1 = "abcde".codePoints();

// [61, 62, 63, 64, 65]
System.out.println(ret1.mapToObj(Integer::toHexString).toList());

// Unicodeで 0x304b = か, 0x304d = き, 0x304f = く, 0x3051 = け, 0x3053 = こ
final var ret2 = "かきくけこ".codePoints();

// [304b, 304d, 304f, 3051, 3053]
System.out.println(ret2.mapToObj(Integer::toHexString).toList());
// サロゲート・コード・ポイントも1文字にマッピングされます。
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "ab" + surrogate;
System.out.println(s); // "ab𩸽"

final var ret = s.codePoints();

ret.forEach(c -> {
    System.out.println("%x : %c".formatted(c, c));
});

// 結果
// ↓
// "61 : a"
// "62 : b"
// "29e3d : 𩸽"

int compareTo (String anotherString)

2つの文字列を辞書的に比較します。

System.out.println("Cake".compareTo("Book")); // 1
System.out.println("Cake".compareTo("Stone")); // -16

System.out.println("Book".compareTo("Book")); // 0
System.out.println("Book".compareTo("book")); // -32
System.out.println("a".compareTo("a")); // 0
System.out.println("a".compareTo("A")); // 32
System.out.println("A".compareTo("a")); // -32
System.out.println("A".compareTo("A")); // 0

System.out.println("a".compareTo("b")); // -1
System.out.println("b".compareTo("a")); // 1

System.out.println("A".compareTo("b")); // -33
System.out.println("b".compareTo("A")); // 33

System.out.println("a".compareTo("B")); // 31
System.out.println("B".compareTo("a")); // -31

int compareToIgnoreCase (String str)

大文字と小文字の区別なしで、2つの文字列を辞書的に比較します。

System.out.println("Cake".compareToIgnoreCase("Book")); // 1
System.out.println("Cake".compareToIgnoreCase("Stone")); // -16

System.out.println("Book".compareToIgnoreCase("Book")); // 0
System.out.println("Book".compareToIgnoreCase("book")); // 0
System.out.println("a".compareToIgnoreCase("a")); // 0
System.out.println("a".compareToIgnoreCase("A")); // 0
System.out.println("A".compareToIgnoreCase("a")); // 0
System.out.println("A".compareToIgnoreCase("A")); // 0

System.out.println("a".compareToIgnoreCase("b")); // -1
System.out.println("b".compareToIgnoreCase("a")); // 1

System.out.println("A".compareToIgnoreCase("b")); // -1
System.out.println("b".compareToIgnoreCase("A")); // 1

System.out.println("a".compareToIgnoreCase("B")); // -1
System.out.println("B".compareToIgnoreCase("a")); // 1

String concat (String str)

指定された文字列をこの文字列の最後に連結します。

final var ret1 = "cares".concat("s");
System.out.println(ret1); // "caress"

final var ret2 = "to".concat("get").concat("her");
System.out.println(ret2); // "together"

boolean contains (CharSequence s)

この文字列が指定されたchar値のシーケンスを含む場合に限りtrueを返します。

final var s = "abcde";

System.out.println(s.contains("a")); // true
System.out.println(s.contains("abc")); // true
System.out.println(s.contains("z")); // false
System.out.println(s.contains("ace")); // false
final var s = "あいうえお";

System.out.println(s.contains("あ")); // true
System.out.println(s.contains("うえお")); // true
System.out.println(s.contains("か")); // false
System.out.println(s.contains("a")); // false

boolean contentEquals (CharSequence cs)

この文字列と指定されたCharSequenceを比較します。

final var s = "abc";
System.out.println(s.contentEquals("abc")); // true
System.out.println(s.contentEquals("xyz")); // false

// StringBuilderもCharSequenceなので直接使えます。
final var cs = new StringBuilder();
cs.append('a');

System.out.println(s.contentEquals(cs)); // false

cs.append('b');
cs.append('c');

System.out.println(s.contentEquals(cs)); // true

boolean contentEquals (StringBuffer sb)

この文字列と指定されたStringBufferを比較します。

final var s = "abc";

final var sb = new StringBuffer();
sb.append('a');

System.out.println(s.contentEquals(sb)); // false

sb.append('b');
sb.append('c');

System.out.println(s.contentEquals(sb)); // true

static String copyValueOf (char[] data)

valueOf(char[])と同等です。

final char[] data = {'a', 'b', 'c'};
final var ret = String.copyValueOf(data);

System.out.println(ret); // "abc"
final char[] data = {'あ', 'い', 'う'};
final var ret = String.copyValueOf(data);

System.out.println(ret); // "あいう"

static String copyValueOf (char[] data, int offset, int count)

valueOf(char[], int, int)と同等です。

final char[] data = {'a', 'b', 'c'};

System.out.println(String.copyValueOf(data, 0, 0)); // ""
System.out.println(String.copyValueOf(data, 0, 1)); // "a"
System.out.println(String.copyValueOf(data, 0, 2)); // "ab"
System.out.println(String.copyValueOf(data, 0, 3)); // "abc"
//String.copyValueOf(data, 0, 4); // IndexOutOfBoundsException

System.out.println(String.copyValueOf(data, 1, 2)); // "bc"
System.out.println(String.copyValueOf(data, 2, 1)); // "c"
final char[] data = {'あ', 'い', 'う'};

System.out.println(String.copyValueOf(data, 0, 3)); // "あいう"
System.out.println(String.copyValueOf(data, 1, 2)); // "いう"

Optional<String> describeConstable ()

このインスタンス自体の名目記述子を含むOptionalを返します。

final var ret = "abcd".describeConstable();
System.out.println(ret); // Optional[abcd]

boolean endsWith (String suffix)

この文字列が、指定された接尾辞で終るかどうかを判定します。

final var s = "abcd";

System.out.println(s.endsWith("abcd")); // true
System.out.println(s.endsWith("bcd")); // true
System.out.println(s.endsWith("cd")); // true
System.out.println(s.endsWith("d")); // true
System.out.println(s.endsWith("")); // true

System.out.println(s.endsWith("a")); // false
System.out.println(s.endsWith("ab")); // false
System.out.println(s.endsWith("abc")); // false

boolean equals (Object anObject)

この文字列と指定されたオブジェクトを比較します。

final var s = "abc";

System.out.println(s.equals("")); // false
System.out.println(s.equals("a")); // false
System.out.println(s.equals("ab")); // false
System.out.println(s.equals("abc")); // true
System.out.println(s.equals("abcd")); // false

System.out.println(s.equals("ABC")); // false
final var s = "abc";
final var sb = new StringBuilder("abc");

System.out.println(s.equals(sb)); // false
System.out.println(s.contentEquals(sb)); // true

boolean equalsIgnoreCase (String anotherString)

大文字と小文字を区別せずに、このStringを別のStringと比較します。

final var s = "abc";

System.out.println(s.equalsIgnoreCase("")); // false
System.out.println(s.equalsIgnoreCase("a")); // false
System.out.println(s.equalsIgnoreCase("ab")); // false
System.out.println(s.equalsIgnoreCase("abc")); // true
System.out.println(s.equalsIgnoreCase("abcd")); // false

System.out.println(s.equalsIgnoreCase("ABC")); // true

static String format (String format, Object... args)

指定された書式の文字列と引数を使って、書式付き文字列を返します。

System.out.println(String.format("b : %b", true));  // "b : true"
System.out.println(String.format("B : %B", false)); // "B : FALSE"

System.out.println(String.format("h : %h", "abcd")); // "h : 2d9442"
System.out.println(String.format("H : %H", LocalTime.of(12, 30))); // "H : 6103F8ED"

System.out.println(String.format("s : %s", "abcd")); // "s : abcd"
System.out.println(String.format("S : %S", "abcd")); // "S : ABCD"

System.out.println(String.format("c : %c", 'z')); // "c : z"
System.out.println(String.format("C : %C", 'z')); // "C : Z"

System.out.println(String.format("d : %d", 123)); // "d : 123"
System.out.println(String.format("o : %o", 123)); // "o : 173"

System.out.println(String.format("x : %x", 123)); // "x : 7b"
System.out.println(String.format("X : %X", 123)); // "X : 7B"

System.out.println(String.format("e : %e", 0.12)); // "e : 1.200000e-01"
System.out.println(String.format("E : %E", 0.12)); // "E : 1.200000E-01"

System.out.println(String.format("f : %f", 1.400004)); // "f : 1.400004"
System.out.println(String.format("g : %g", 1.400004)); // "g : 1.40000"

System.out.println(String.format("a : %a", 0.12)); // "a : 0x1.eb851eb851eb8p-4"
System.out.println(String.format("A : %A", 0.12)); // "A : 0X1.EB851EB851EB8P-4"

final var date = LocalDate.of(2021, 3, 10);
System.out.println(date); // 2021-03-10
System.out.println(String.format("%tY %tm %te", date, date, date)); // "2021 03 10"

static String format (Locale l, String format, Object... args)

指定されたロケール、書式文字列、および引数を使って、フォーマットされた文字列を返します。

final var date = LocalDate.of(2021, 3, 10);
System.out.println(date); // 2021-03-10

final var ret1 = String.format(Locale.JAPAN, "%tY %tB %te %tA", date, date, date, date);
System.out.println(ret1); // 2021 3月 10 水曜日

final var ret2 = String.format(Locale.ENGLISH, "%tY %tB %te %tA", date, date, date, date);
System.out.println(ret2); // 2021 March 10 Wednesday

String formatted (Object... args)

この文字列を書式文字列として使用し、指定された引数を書式設定します。

System.out.println("b : %b".formatted(true));  // "b : true"
System.out.println("B : %B".formatted(false)); // "B : FALSE"

System.out.println("h : %h".formatted("abcd")); // "h : 2d9442"
System.out.println("H : %H".formatted(LocalTime.of(12, 30))); // "H : 6103F8ED"

System.out.println("s : %s".formatted("abcd")); // "s : abcd"
System.out.println("S : %S".formatted("abcd")); // "S : ABCD"

System.out.println("c : %c".formatted('z')); // "c : z"
System.out.println("C : %C".formatted('z')); // "C : Z"

System.out.println("d : %d".formatted(123)); // "d : 123"
System.out.println("o : %o".formatted(123)); // "o : 173"

System.out.println("x : %x".formatted(123)); // "x : 7b"
System.out.println("X : %X".formatted(123)); // "X : 7B"

System.out.println("e : %e".formatted(0.12)); // "e : 1.200000e-01"
System.out.println("E : %E".formatted(0.12)); // "E : 1.200000E-01"

System.out.println("f : %f".formatted(1.400004)); // "f : 1.400004"
System.out.println("g : %g".formatted(1.400004)); // "g : 1.40000"

System.out.println("a : %a".formatted(0.12)); // "a : 0x1.eb851eb851eb8p-4"
System.out.println("A : %A".formatted(0.12)); // "A : 0X1.EB851EB851EB8P-4"

final var date = LocalDate.of(2021, 3, 10);
System.out.println(date); // 2021-03-10
System.out.println("%tY %tm %te".formatted(date, date, date)); // "2021 03 10"

byte[] getBytes ()

default charsetを使用してこのStringをバイトのシーケンスにエンコードし、結果を新しいバイト配列に格納します。

final var ret = "abcd".getBytes();

// [97, 98, 99, 100]
System.out.println(Arrays.toString(ret));
// ※ 環境によって違う場合があります。
System.out.println(Charset.defaultCharset());   // UTF-8

final var s = "あいうえお";
final var ret = s.getBytes();

// [-29, -127, -126, -29, -127, -124, -29, -127, -122, -29, -127, -120, -29, -127, -118]
System.out.println(Arrays.toString(ret));

final var utf8 = s.getBytes(StandardCharsets.UTF_8);
System.out.println(Arrays.equals(ret, utf8)); // true

final var sjis = s.getBytes("Shift_JIS");
System.out.println(Arrays.equals(ret, sjis)); // false

void getBytes (int srcBegin, int srcEnd, byte[] dst, int dstBegin)

非推奨。 このメソッドでは、文字からバイトへの変換が正しく行われません。

非推奨です。

byte[] getBytes (String charsetName)

指定された文字セットを使用してこのStringをバイト・シーケンスにエンコードし、結果を新規バイト配列に格納します。

final var s = "あいうえお";

final var utf8 = s.getBytes("UTF-8");

// [-29, -127, -126, -29, -127, -124, -29, -127, -122, -29, -127, -120, -29, -127, -118]
System.out.println(Arrays.toString(utf8));
System.out.println(new String(utf8, "UTF-8")); // "あいうえお"

final var sjis = s.getBytes("Shift_JIS");

// [-126, -96, -126, -94, -126, -92, -126, -90, -126, -88]
System.out.println(Arrays.toString(sjis));
System.out.println(new String(sjis, "Shift_JIS")); // "あいうえお"

byte[] getBytes (Charset charset)

指定された文字セットを使用してこのStringをバイト・シーケンスに符号化し、結果を新規バイト配列に格納します。

final var s = "あいうえお";

final var utf8 = s.getBytes(StandardCharsets.UTF_8);

// [-29, -127, -126, -29, -127, -124, -29, -127, -122, -29, -127, -120, -29, -127, -118]
System.out.println(Arrays.toString(utf8));
System.out.println(new String(utf8, StandardCharsets.UTF_8)); // "あいうえお"

final var sjis = s.getBytes(Charset.forName("Shift_JIS"));

// [-126, -96, -126, -94, -126, -92, -126, -90, -126, -88]
System.out.println(Arrays.toString(sjis));
System.out.println(new String(sjis, Charset.forName("Shift_JIS"))); // "あいうえお"

void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin)

この文字列から、コピー先の文字配列に文字をコピーします。

final var s = "abcde";

final var chars1 = new char[5];
s.getChars(0, 5, chars1, 0);
System.out.println(Arrays.toString(chars1)); // [a, b, c, d, e]

final var chars2 = new char[5];
s.getChars(1, 3, chars2, 0);
System.out.println(Arrays.toString(chars2)); // [b, c,  ,  ,  ]

final var chars3 = new char[5];
s.getChars(0, 2, chars3, 3);
System.out.println(Arrays.toString(chars3)); // [ ,  ,  , a, b]

int hashCode ()

この文字列のハッシュ・コードを返します。

System.out.println("".hashCode());  // 0
System.out.println("a".hashCode()); // 97
System.out.println("ab".hashCode()); // 3105
System.out.println("123".hashCode()); // 48690
final var s = """
        abcdefghijklmnopqrstuvwxyz
        ABCDEFGHIJKLMNOPQRSTUVWXYZ
        123456790
        """;

System.out.println(s.hashCode()); // 573751039

String indent (int n)

nの値に基づいてこの文字列の各行のインデントを調整し、行の終了文字を正規化します。

final var s = """
        Book
        Cake
        Tree
        Stone
        """;
// """
// Cake
// Tree
// Stone
// """
System.out.println(s);

// """
// Book
// Cake
// Tree
// Stone
// """
System.out.println(s.indent(0));

// """
//  Book
//  Cake
//  Tree
//  Stone
// """
System.out.println(s.indent(1));

// """
//   Book
//   Cake
//   Tree
//   Stone
// """
System.out.println(s.indent(2));

int indexOf (int ch)

この文字列内で、指定された文字が最初に出現する位置のインデックスを返します。

final var s = "abcXY";

System.out.println(s.indexOf('a')); // 0
System.out.println(s.indexOf('b')); // 1
System.out.println(s.indexOf('c')); // 2
System.out.println(s.indexOf('d')); // -1
System.out.println(s.indexOf('X')); // 3
System.out.println(s.indexOf('Y')); // 4
System.out.println(s.indexOf('Z')); // -1
final var s = "abcabc";
System.out.println(s.indexOf('a')); // 0
System.out.println(s.indexOf('b')); // 1
System.out.println(s.indexOf('c')); // 2
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.indexOf('a')); // 0

// 0x29e3d = 𩸽のUnicodeポイント
System.out.println(s.indexOf(0x29e3d)); // 1

System.out.println(s.indexOf('b')); // 3

int indexOf (int ch, int fromIndex)

この文字列内で、指定されたインデックスから検索を開始し、指定された文字が最初に出現する位置のインデックスを返します。

final var s = "abcabc";

System.out.println(s.indexOf('a', -1)); // 0
System.out.println(s.indexOf('a', 0)); // 0
System.out.println(s.indexOf('a', 1)); // 3
System.out.println(s.indexOf('a', 2)); // 3
System.out.println(s.indexOf('a', 3)); // 3
System.out.println(s.indexOf('a', 4)); // -1
System.out.println(s.indexOf('a', 5)); // -1
System.out.println(s.indexOf('a', 6)); // -1

System.out.println(s.indexOf('b', 0)); // 1
System.out.println(s.indexOf('b', 1)); // 1
System.out.println(s.indexOf('b', 2)); // 4
System.out.println(s.indexOf('b', 3)); // 4
System.out.println(s.indexOf('b', 4)); // 4
System.out.println(s.indexOf('b', 5)); // -1

System.out.println(s.indexOf('c', 0)); // 2
System.out.println(s.indexOf('c', 1)); // 2
System.out.println(s.indexOf('c', 2)); // 2
System.out.println(s.indexOf('c', 3)); // 5
System.out.println(s.indexOf('c', 4)); // 5
System.out.println(s.indexOf('c', 5)); // 5
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.indexOf('a', 0)); // 0
System.out.println(s.indexOf('a', 1)); // -1
System.out.println(s.indexOf('a', 2)); // -1
System.out.println(s.indexOf('a', 3)); // -1

// 0x29e3d = 𩸽のUnicodeポイント
System.out.println(s.indexOf(0x29e3d, 0)); // 1
System.out.println(s.indexOf(0x29e3d, 1)); // 1
System.out.println(s.indexOf(0x29e3d, 2)); // -1
System.out.println(s.indexOf(0x29e3d, 3)); // -1

System.out.println(s.indexOf('b', 0)); // 3
System.out.println(s.indexOf('b', 1)); // 3
System.out.println(s.indexOf('b', 2)); // 3
System.out.println(s.indexOf('b', 3)); // 3
System.out.println(s.indexOf('b', 4)); // -1

int indexOf (String str)

この文字列内で、指定された部分文字列が最初に出現する位置のインデックスを返します。

final var s = "abcabc";

System.out.println(s.indexOf("a")); // 0
System.out.println(s.indexOf("ab")); // 0
System.out.println(s.indexOf("abc")); // 0
System.out.println(s.indexOf("bc")); // 1
System.out.println(s.indexOf("c")); // 2
System.out.println(s.indexOf("cab")); // 2

System.out.println(s.indexOf("abcd")); // -1
System.out.println(s.indexOf("ac")); // -1
System.out.println(s.indexOf("z")); // -1
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.indexOf("a")); // 0
System.out.println(s.indexOf(surrogate)); // 1
System.out.println(s.indexOf("b")); // 3

int indexOf (String str, int fromIndex)

指定されたインデックス以降で、指定された部分文字列がこの文字列内で最初に出現する位置のインデックスを返します。

final var s = "abcabc";

System.out.println(s.indexOf("ab", -1)); // 0
System.out.println(s.indexOf("ab", 0)); // 0
System.out.println(s.indexOf("ab", 1)); // 3
System.out.println(s.indexOf("ab", 2)); // 3
System.out.println(s.indexOf("ab", 3)); // 3
System.out.println(s.indexOf("ab", 4)); // -1
System.out.println(s.indexOf("ab", 5)); // -1
System.out.println(s.indexOf("ab", 6)); // -1

System.out.println(s.indexOf("bc", 0)); // 1
System.out.println(s.indexOf("bc", 1)); // 1
System.out.println(s.indexOf("bc", 2)); // 4
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.indexOf("a", 0)); // 0
System.out.println(s.indexOf("a", 1)); // -1

System.out.println(s.indexOf(surrogate, 0)); // 1
System.out.println(s.indexOf(surrogate, 1)); // 1
System.out.println(s.indexOf(surrogate, 2)); // -1
System.out.println(s.indexOf(surrogate, 3)); // -1

System.out.println(s.indexOf("b", 0)); // 3
System.out.println(s.indexOf("b", 1)); // 3
System.out.println(s.indexOf("b", 2)); // 3
System.out.println(s.indexOf("b", 3)); // 3
System.out.println(s.indexOf("b", 4)); // -1

String intern ()

文字列オブジェクトの正準表現を返します。

final var s1 = new String("abc");
final var s2 = new String("abc");

final var ret1 = s1.intern();
System.out.println(ret1); // "abc"

final var ret2 = s2.intern();
System.out.println(ret2); // "abc"

System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
System.out.println(ret1 == ret2); // true

boolean isBlank ()

文字列が空かwhite spaceコード・ポイントのみが含まれる場合はtrueを戻し、それ以外の場合はfalseを返します。

System.out.println("".isBlank()); // true
System.out.println(" ".isBlank()); // true
System.out.println("     ".isBlank()); // true
System.out.println("\t".isBlank()); // true
System.out.println("\n".isBlank()); // true

System.out.println("abc".isBlank()); // false
System.out.println("a b c".isBlank()); // false

// 全角スペース
System.out.println(" ".isBlank()); // true

boolean isEmpty ()

length()が0の場合にのみ、trueを返します。

System.out.println("".isEmpty()); // true
System.out.println(" ".isEmpty()); // false
System.out.println("\n".isEmpty()); // false
System.out.println("\0".isEmpty()); // false
System.out.println("abc".isEmpty()); // false

static String join (CharSequence delimiter, CharSequence... elements)

指定されたdelimiterのコピーを使用して結合されたCharSequence要素のコピーからなる新しいStringを返します。

System.out.println(String.join("-", "Java", "is", "cool")); // "Java-is-cool"
System.out.println(String.join("->", "A", "B", "C")); // "A->B->C"

System.out.println(String.join("-")); // ""
System.out.println(String.join("-", "", "a", "", "b")); // "-a--b"

static String join (CharSequence delimiter, Iterable<? extends CharSequence> elements)

指定されたdelimiterのコピーを使用して結合されたCharSequence要素のコピーからなる新しいStringを返します。

System.out.println(String.join("-", List.of("Java", "is", "cool"))); // "Java-is-cool"
System.out.println(String.join("->", List.of("A", "B", "C"))); // "A->B->C"

System.out.println(String.join("-", List.of())); // ""
System.out.println(String.join("-", List.of("", "a", "", "b"))); // "-a--b"

int lastIndexOf (int ch)

この文字列内で、指定された文字が最後に出現する位置のインデックスを返します。

final var s = "abcXY";

System.out.println(s.lastIndexOf('a')); // 0
System.out.println(s.lastIndexOf('b')); // 1
System.out.println(s.lastIndexOf('c')); // 2
System.out.println(s.lastIndexOf('d')); // -1
System.out.println(s.lastIndexOf('X')); // 3
System.out.println(s.lastIndexOf('Y')); // 4
System.out.println(s.lastIndexOf('Z')); // -1
final var s = "abcabc";
System.out.println(s.lastIndexOf('a')); // 3
System.out.println(s.lastIndexOf('b')); // 4
System.out.println(s.lastIndexOf('c')); // 5
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.lastIndexOf('a')); // 0

// 0x29e3d = 𩸽のUnicodeポイント
System.out.println(s.lastIndexOf(0x29e3d)); // 1

System.out.println(s.lastIndexOf('b')); // 3

int lastIndexOf (int ch, int fromIndex)

この文字列内で、指定された文字が最後に出現する位置のインデックスを返します(検索は指定されたインデックスから開始され、先頭方向に行われる)。

final var s = "abcabc";

System.out.println(s.lastIndexOf('a', 5)); // 3
System.out.println(s.lastIndexOf('a', 4)); // 3
System.out.println(s.lastIndexOf('a', 3)); // 3
System.out.println(s.lastIndexOf('a', 2)); // 0
System.out.println(s.lastIndexOf('a', 1)); // 0
System.out.println(s.lastIndexOf('a', 0)); // 0

System.out.println(s.lastIndexOf('b', 5)); // 4
System.out.println(s.lastIndexOf('b', 4)); // 4
System.out.println(s.lastIndexOf('b', 3)); // 1
System.out.println(s.lastIndexOf('b', 2)); // 1
System.out.println(s.lastIndexOf('b', 1)); // 1
System.out.println(s.lastIndexOf('b', 0)); // -1

System.out.println(s.lastIndexOf('c', 5)); // 5
System.out.println(s.lastIndexOf('c', 4)); // 2
System.out.println(s.lastIndexOf('c', 3)); // 2
System.out.println(s.lastIndexOf('c', 2)); // 2
System.out.println(s.lastIndexOf('c', 1)); // -1
System.out.println(s.lastIndexOf('c', 0)); // -1
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.lastIndexOf('a', 3)); // 0
System.out.println(s.lastIndexOf('a', 2)); // 0
System.out.println(s.lastIndexOf('a', 1)); // 0
System.out.println(s.lastIndexOf('a', 0)); // 0

// 0x29e3d = 𩸽のUnicodeポイント
System.out.println(s.lastIndexOf(0x29e3d, 3)); // 1
System.out.println(s.lastIndexOf(0x29e3d, 2)); // 1
System.out.println(s.lastIndexOf(0x29e3d, 1)); // 1
System.out.println(s.lastIndexOf(0x29e3d, 0)); // -1

System.out.println(s.lastIndexOf('b', 4)); // 3
System.out.println(s.lastIndexOf('b', 3)); // 3
System.out.println(s.lastIndexOf('b', 2)); // -1
System.out.println(s.lastIndexOf('b', 1)); // -1
System.out.println(s.lastIndexOf('b', 0)); // -1

int lastIndexOf (String str)

この文字列内で、指定された部分文字列が最後に出現する位置のインデックスを返します。

final var s = "abcabc";

System.out.println(s.lastIndexOf("a")); // 3
System.out.println(s.lastIndexOf("ab")); // 3
System.out.println(s.lastIndexOf("abc")); // 3
System.out.println(s.lastIndexOf("bc")); // 4
System.out.println(s.lastIndexOf("c")); // 5
System.out.println(s.lastIndexOf("cab")); // 2

System.out.println(s.lastIndexOf("abcd")); // -1
System.out.println(s.lastIndexOf("ac")); // -1
System.out.println(s.lastIndexOf("z")); // -1
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.lastIndexOf("a")); // 0
System.out.println(s.lastIndexOf(surrogate)); // 1
System.out.println(s.lastIndexOf("b")); // 3

int lastIndexOf (String str, int fromIndex)

この文字列内で、指定された部分文字列が最後に出現する位置のインデックスを返します(検索は指定されたインデックスから開始され、先頭方向に行われる)。

final var s = "abcabc";

System.out.println(s.lastIndexOf("ab", 5)); // 3
System.out.println(s.lastIndexOf("ab", 4)); // 3
System.out.println(s.lastIndexOf("ab", 3)); // 3
System.out.println(s.lastIndexOf("ab", 2)); // 0
System.out.println(s.lastIndexOf("ab", 1)); // 0
System.out.println(s.lastIndexOf("ab", 0)); // 0

System.out.println(s.lastIndexOf("bc", 5)); // 4
System.out.println(s.lastIndexOf("bc", 4)); // 4
System.out.println(s.lastIndexOf("bc", 3)); // 1
System.out.println(s.lastIndexOf("bc", 2)); // 1
System.out.println(s.lastIndexOf("bc", 1)); // 1
System.out.println(s.lastIndexOf("bc", 0)); // -1

System.out.println(s.lastIndexOf("ca", 5)); // 2
System.out.println(s.lastIndexOf("ca", 4)); // 2
System.out.println(s.lastIndexOf("ca", 3)); // 2
System.out.println(s.lastIndexOf("ca", 2)); // 2
System.out.println(s.lastIndexOf("ca", 1)); // -1
System.out.println(s.lastIndexOf("ca", 0)); // -1
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.lastIndexOf("a", 3)); // 0
System.out.println(s.lastIndexOf("a", 2)); // 0
System.out.println(s.lastIndexOf("a", 1)); // 0
System.out.println(s.lastIndexOf("a", 0)); // 0

System.out.println(s.lastIndexOf(surrogate, 3)); // 1
System.out.println(s.lastIndexOf(surrogate, 2)); // 1
System.out.println(s.lastIndexOf(surrogate, 1)); // 1
System.out.println(s.lastIndexOf(surrogate, 0)); // -1

System.out.println(s.lastIndexOf("b", 3)); // 3
System.out.println(s.lastIndexOf("b", 2)); // -1
System.out.println(s.lastIndexOf("b", 1)); // -1
System.out.println(s.lastIndexOf("b", 0)); // -1

int length ()

この文字列の長さを戻します。

System.out.println("".length()); // 0
System.out.println("abc".length()); // 3
System.out.println("あいうえお".length()); // 5
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.length()); // 4
System.out.println(s.codePoints().count()); // 3

Stream<String> lines ()

この文字列から抽出された行のストリームを、行終了記号で区切って返します。

final var s = """
        Book
        Cake
        Stone
        """;
final var ret = s.lines();
System.out.println(ret.toList()); // [Book, Cake, Stone]
final var s = """

        Book

        Cake

        Stone

        """;
final var ret = s.lines();
System.out.println(ret.toList()); // [, Book, , Cake, , Stone, ]
final var ret = "".lines();
System.out.println(ret.toList()); // []

boolean matches (String regex)

この文字列が、指定された正規表現と一致するかどうかを判定します。

final var s = "java is cool";

System.out.println(s.matches("java")); // false
System.out.println(s.matches("java.*")); // true

System.out.println(s.matches(".*cool")); // true
final var s1 = "Book";
final var s2 = "Cake";
final var s3 = "Stone";

System.out.println(s1.matches("Book|Cake")); // true
System.out.println(s2.matches("Book|Cake")); // true
System.out.println(s3.matches("Book|Cake")); // false

int offsetByCodePoints (int index, int codePointOffset)

このString内で、指定されたindexからcodePointOffsetコード・ポイント分だけオフセットされた位置のインデックスを返します。

final var s = "abc";

//s.offsetByCodePoints(0, -1); // IndexOutOfBoundsException
System.out.println(s.offsetByCodePoints(0, 0)); // 0
System.out.println(s.offsetByCodePoints(0, 1)); // 1
System.out.println(s.offsetByCodePoints(0, 2)); // 2
System.out.println(s.offsetByCodePoints(0, 3)); // 3

System.out.println(s.offsetByCodePoints(1, 0)); // 1
System.out.println(s.offsetByCodePoints(1, 1)); // 2
System.out.println(s.offsetByCodePoints(1, 2)); // 3
// サロゲート・コード・ポイントの例
final var surrogate = "\uD867\uDE3D";  // "𩸽"という1文字
System.out.println(surrogate); // "𩸽"

final var s = "a" + surrogate + "b";
System.out.println(s); // "a𩸽b"

System.out.println(s.offsetByCodePoints(0, 0)); // 0
System.out.println(s.offsetByCodePoints(0, 1)); // 1
System.out.println(s.offsetByCodePoints(0, 2)); // 3
System.out.println(s.offsetByCodePoints(0, 3)); // 4

boolean regionMatches (boolean ignoreCase, int toffset, String other, int ooffset, int len)

2つの文字列領域が等しいかどうかを判定します。

final var s = "abcde";

// ignoreCase falseの場合
System.out.println(s.regionMatches(false, 0, "abcde", 0, 5)); // true
System.out.println(s.regionMatches(false, 0, "bcdef", 0, 5)); // false
System.out.println(s.regionMatches(false, 0, "ABCDE", 0, 5)); // false

System.out.println(s.regionMatches(false, 0, "bcd", 0, 3)); // false
System.out.println(s.regionMatches(false, 1, "bcd", 0, 3)); // true
System.out.println(s.regionMatches(false, 2, "bcd", 0, 3)); // false

System.out.println(s.regionMatches(false, 0, "012abcde345", 0, 11)); // false
System.out.println(s.regionMatches(false, 0, "012abcde345", 0, 5)); // false
System.out.println(s.regionMatches(false, 0, "012abcde345", 3, 5)); // true

// ignoreCase trueの場合
System.out.println(s.regionMatches(true, 0, "abcde", 0, 5)); // true
System.out.println(s.regionMatches(true, 0, "bcdef", 0, 5)); // false
System.out.println(s.regionMatches(true, 0, "ABCDE", 0, 5)); // true

boolean regionMatches (int toffset, String other, int ooffset, int len)

2つの文字列領域が等しいかどうかを判定します。

final var s = "abcde";

System.out.println(s.regionMatches(0, "abcde", 0, 5)); // true
System.out.println(s.regionMatches(0, "bcdef", 0, 5)); // false
System.out.println(s.regionMatches(0, "ABCDE", 0, 5)); // false

System.out.println(s.regionMatches(0, "bcd", 0, 3)); // false
System.out.println(s.regionMatches(1, "bcd", 0, 3)); // true
System.out.println(s.regionMatches(2, "bcd", 0, 3)); // false

System.out.println(s.regionMatches(0, "012abcde345", 0, 11)); // false
System.out.println(s.regionMatches(0, "012abcde345", 0, 5)); // false
System.out.println(s.regionMatches(0, "012abcde345", 3, 5)); // true

String repeat (int count)

この文字列を連結した値がcount回繰り返される文字列を返します。

System.out.println("A".repeat(0)); // ""
System.out.println("A".repeat(1)); // "A"
System.out.println("A".repeat(2)); // "AA"
System.out.println("A".repeat(3)); // "AAA"

System.out.println("abc".repeat(0)); // ""
System.out.println("abc".repeat(1)); // "abc"
System.out.println("abc".repeat(2)); // "abcabc"

System.out.println("".repeat(0)); // ""
System.out.println("".repeat(1)); // ""

String replace (char oldChar, char newChar)

この文字列内にあるすべてのoldCharをnewCharに置換した結果生成される文字列を返します。

final var s = "abcd";

System.out.println(s.replace('a', 'X')); // "Xbcd"
System.out.println(s.replace('b', 'Y')); // "aYcd"
System.out.println(s.replace('c', 'Z')); // "abZd"
final var s = "aabbcc";

System.out.println(s.replace('a', 'X')); // "XXbbcc"
System.out.println(s.replace('b', 'Y')); // "aaYYcc"

String replace (CharSequence target, CharSequence replacement)

リテラル・ターゲット・シーケンスに一致するこの文字列の部分文字列を、指定されたリテラル置換シーケンスに置き換えます。

final var s = "abcd";

System.out.println(s.replace("a", "X")); // "Xbcd"
System.out.println(s.replace("abc", "XYZ")); // "XYZd"
System.out.println(s.replace("ab", "")); // "cd"
final var s = "abcabc";

System.out.println(s.replace("a", "X")); // "XbcXbc"
System.out.println(s.replace("bc", "YYZZ")); // "aYYZZaYYZZ"

String replaceAll (String regex, String replacement)

指定された正規表現に一致する、この文字列の各部分文字列に対し、指定された置換を実行します。

final var s = "javaAAABBB";

System.out.println(s.replaceAll("java.", "x")); // "xAABBB"
System.out.println(s.replaceAll("A.", "y")); // "javayyBB"
System.out.println(s.replaceAll(".", "z")); // "zzzzzzzzzz"

String replaceFirst (String regex, String replacement)

指定された正規表現に一致する、この文字列の最初の部分文字列に対し、指定された置換を実行します。

final var s = "javaAAABBB";

System.out.println(s.replaceFirst("java.", "x")); // "xAABBB"
System.out.println(s.replaceFirst("A.", "y")); // "javayABBB"
System.out.println(s.replaceFirst(".", "z")); // "zavaAAABBB"

String resolveConstantDesc (MethodHandles.Lookup lookup)

このインスタンスをConstantDescとして解決します。その結果がインスタンス自体です。

final var ret = "abcd".resolveConstantDesc(MethodHandles.lookup());
System.out.println(ret); // "abcd"

String[] split (String regex)

この文字列を、指定された正規表現に一致する位置で分割します。

final var s = "a-b-c";

System.out.println(Arrays.toString(s.split("-"))); // [a, b, c]
System.out.println(Arrays.toString(s.split("b"))); // [a-, -c]
System.out.println(Arrays.toString(s.split("X"))); // [a-b-c]
final var s = "boo:and:foo";

System.out.println(Arrays.toString(s.split(":"))); // [boo, and, foo]
System.out.println(Arrays.toString(s.split("o"))); // [b, , :and:f]
final var s = "a-b>c";

System.out.println(Arrays.toString(s.split("-"))); // [a, b>c]
System.out.println(Arrays.toString(s.split(">"))); // [a-b, c]
System.out.println(Arrays.toString(s.split("(-|>)"))); // [a, b, c]

String[] split (String regex, int limit)

この文字列を、指定された正規表現に一致する位置で分割します。

final var s = "a-b-c";

System.out.println(Arrays.toString(s.split("-", 0))); // [a, b, c]
System.out.println(Arrays.toString(s.split("-", 1))); // [a-b-c]
System.out.println(Arrays.toString(s.split("-", 2))); // [a, b-c]
System.out.println(Arrays.toString(s.split("-", 3))); // [a, b, c]
final var s = "boo:and:foo";

System.out.println(Arrays.toString(s.split(":", 2))); // [boo, and:foo]
System.out.println(Arrays.toString(s.split(":", 5))); // [boo, and, foo]
System.out.println(Arrays.toString(s.split(":", -2))); // [boo, and, foo]
System.out.println(Arrays.toString(s.split("o", 5))); // [b, , :and:f, , ]
System.out.println(Arrays.toString(s.split("o", -2))); // [b, , :and:f, , ]
System.out.println(Arrays.toString(s.split("o", 0))); // [b, , :and:f]
final var s = "a-b>c";

System.out.println(Arrays.toString(s.split("-", 1))); // [a-b>c]
System.out.println(Arrays.toString(s.split("-", 2))); // [a, b>c]
System.out.println(Arrays.toString(s.split("-", 3))); // [a, b>c]

System.out.println(Arrays.toString(s.split(">", 1))); // [a-b>c]
System.out.println(Arrays.toString(s.split(">", 2))); // [a-b, c]
System.out.println(Arrays.toString(s.split(">", 3))); // [a-b, c]

System.out.println(Arrays.toString(s.split("(-|>)", 1))); // [a-b>c]
System.out.println(Arrays.toString(s.split("(-|>)", 2))); // [a, b>c]
System.out.println(Arrays.toString(s.split("(-|>)", 3))); // [a, b, c]

boolean startsWith (String prefix)

この文字列が、指定された接頭辞で始まるかどうかを判定します。

final var s = "abc";

System.out.println(s.startsWith("a")); // true
System.out.println(s.startsWith("ab")); // true
System.out.println(s.startsWith("abc")); // true
System.out.println(s.startsWith("abcd")); // false
System.out.println(s.startsWith("b")); // false
System.out.println(s.startsWith("c")); // false

boolean startsWith (String prefix, int toffset)

この文字列の指定されたインデックス以降の部分文字列が、指定された接頭辞で始まるかどうかを判定します。

final var s = "abc";

System.out.println(s.startsWith("a", 0)); // true
System.out.println(s.startsWith("a", 1)); // false
System.out.println(s.startsWith("a", 2)); // false

System.out.println(s.startsWith("ab", 0)); // true
System.out.println(s.startsWith("ab", 1)); // false
System.out.println(s.startsWith("ab", 2)); // false

System.out.println(s.startsWith("abc", 0)); // true
System.out.println(s.startsWith("abc", 1)); // false
System.out.println(s.startsWith("abc", 2)); // false

System.out.println(s.startsWith("b", 0)); // false
System.out.println(s.startsWith("b", 1)); // true
System.out.println(s.startsWith("b", 2)); // false

System.out.println(s.startsWith("bc", 0)); // false
System.out.println(s.startsWith("bc", 1)); // true
System.out.println(s.startsWith("bc", 2)); // false

System.out.println(s.startsWith("c", 0)); // false
System.out.println(s.startsWith("c", 1)); // false
System.out.println(s.startsWith("c", 2)); // true

String strip ()

値がこの文字列であり、先頭と末尾のすべてのwhite spaceが削除されている文字列を返します。

関連メソッド:trim()

// 先頭と末尾に半角スペース
final var ret = " abcd ".strip();
System.out.println(ret); // "abcd"
// 先頭と末尾に全角スペース
final var ret = " あいうえお ".strip();
System.out.println(ret); // "あいうえお"
// 空白・タブ・改行・"ABC"・空白・タブ・改行
final var s = " \t\nABC \t\n";

// ※見やすさのために、空白は*、タブは\t、改行は\nとして出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*")
        .replace("\t", "\\t")
        .replace("\n", "\\n");

// "*\t\nABC*\t\n"
System.out.println(func.apply(s));

final var ret = s.strip();

// "ABC"
System.out.println(func.apply(ret));
final var s = "  <html>\n" +
        "    <body>\n" +
        "      <p>Hello</p>\n" +
        "    </body>\n" +
        "  </html>  ";

// ※見やすさのために、空白は*として出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*");

// """
// **<html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>**
// """
System.out.println(func.apply(s));

final var ret = s.strip();

// """
// <html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>
// """
System.out.println(func.apply(ret));

String stripIndent ()

偶然のwhite spaceをあらゆる行の最初と最後から削除して、値がこの文字列である文字列を返します。

// 先頭と末尾に半角スペース
final var ret = " abcd ".stripIndent();
System.out.println(ret); // "abcd"
// 先頭と末尾に全角スペース
final var ret = " あいうえお ".stripIndent();
System.out.println(ret); // "あいうえお"
// 空白・タブ・改行・"ABC"・空白・タブ・改行
final var s = " \t\nABC \t\n";

// ※見やすさのために、空白は*、タブは\t、改行は\nとして出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*")
        .replace("\t", "\\t")
        .replace("\n", "\\n");

// "*\t\nABC*\t\n"
System.out.println(func.apply(s));

final var ret = s.stripIndent();

// "\nABC\n"
System.out.println(func.apply(ret));
final var s = "  <html>\n" +
        "    <body>\n" +
        "      <p>Hello</p>\n" +
        "    </body>\n" +
        "  </html>  ";

// ※見やすさのために、空白は*として出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*");

// """
// **<html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>**
// """
System.out.println(func.apply(s));

// インデント部分だけがよい感じに削除されます。
final var ret = s.stripIndent();

// """
// <html>
// **<body>
// ****<p>Hello</p>
// **</body>
// </html>
// """
System.out.println(func.apply(ret));

String stripLeading ()

すべての先行white spaceが削除されて、値がこの文字列である文字列を返します。

// 先頭と末尾に半角スペース
final var ret = " abcd ".stripLeading();
System.out.println(ret); // "abcd "
// 先頭と末尾に全角スペース
final var ret = " あいうえお ".stripLeading();
System.out.println(ret); // "あいうえお "
// 空白・タブ・改行・"ABC"・空白・タブ・改行
final var s = " \t\nABC \t\n";

// ※見やすさのために、空白は*、タブは\t、改行は\nとして出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*")
        .replace("\t", "\\t")
        .replace("\n", "\\n");

// "*\t\nABC*\t\n"
System.out.println(func.apply(s));

final var ret = s.stripLeading();

// "ABC*\t\n"
System.out.println(func.apply(ret));
final var s = "  <html>\n" +
        "    <body>\n" +
        "      <p>Hello</p>\n" +
        "    </body>\n" +
        "  </html>  ";

// ※見やすさのために、空白は*として出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*");

// """
// **<html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>**
// """
System.out.println(func.apply(s));

final var ret = s.stripLeading();

// """
// <html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>**
// """
System.out.println(func.apply(ret));

String stripTrailing ()

値がこの文字列で、すべての後続white spaceが削除されている文字列を返します。

// 先頭と末尾に半角スペース
final var ret = " abcd ".stripTrailing();
System.out.println(ret); // " abcd"
// 先頭と末尾に全角スペース
final var ret = " あいうえお ".stripTrailing();
System.out.println(ret.stripTrailing()); // " あいうえお"
// 空白・タブ・改行・"ABC"・空白・タブ・改行
final var s = " \t\nABC \t\n";

// ※見やすさのために、空白は*、タブは\t、改行は\nとして出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*")
        .replace("\t", "\\t")
        .replace("\n", "\\n");

// "*\t\nABC*\t\n"
System.out.println(func.apply(s));

final var ret = s.stripTrailing();

// "*\t\nABC"
System.out.println(func.apply(ret));
final var s = "  <html>\n" +
        "    <body>\n" +
        "      <p>Hello</p>\n" +
        "    </body>\n" +
        "  </html>  ";

// ※見やすさのために、空白は*として出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*");

// """
// **<html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>**
// """
System.out.println(func.apply(s));

final var ret = s.stripTrailing();

// """
// **<html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>
// """
System.out.println(func.apply(ret));

CharSequence subSequence (int beginIndex, int endIndex)

このシーケンスのサブシーケンスである文字シーケンスを返します。

final var s = "abcd";

System.out.println(s.subSequence(0, 0)); // ""
System.out.println(s.subSequence(0, 1)); // "a"
System.out.println(s.subSequence(0, 2)); // "ab"
System.out.println(s.subSequence(0, 3)); // "abc"
System.out.println(s.subSequence(0, 4)); // "abcd"
//s.subSequence(0, 5); // IndexOutOfBoundsException

System.out.println(s.subSequence(1, 2)); // "b"
System.out.println(s.subSequence(2, 4)); // "cd"

String substring (int beginIndex)

この文字列の部分文字列である文字列を返します。

final var s = "abcd";

System.out.println(s.substring(0)); // "abcd"
System.out.println(s.substring(1)); // "bcd"
System.out.println(s.substring(2)); // "cd"
System.out.println(s.substring(3)); // "d"
System.out.println(s.substring(4)); // ""
//s.substring(5); // IndexOutOfBoundsException

String substring (int beginIndex, int endIndex)

この文字列の部分文字列である文字列を返します。

final var s = "abcd";

System.out.println(s.substring(0, 0)); // ""
System.out.println(s.substring(0, 1)); // "a"
System.out.println(s.substring(0, 2)); // "ab"
System.out.println(s.substring(0, 3)); // "abc"
System.out.println(s.substring(0, 4)); // "abcd"
//s.substring(0, 5); // IndexOutOfBoundsException

System.out.println(s.substring(1, 2)); // "b"
System.out.println(s.substring(2, 4)); // "cd"

char[] toCharArray ()

この文字列を新しい文字配列に変換します。

final var ret1 = "".toCharArray();
System.out.println(Arrays.toString(ret1)); // []

final var ret2 = "abcd".toCharArray();
System.out.println(Arrays.toString(ret2)); // [a, b, c, d]

final var ret3 = "あいうえお".toCharArray();
System.out.println(Arrays.toString(ret3)); // [あ, い, う, え, お]

String toLowerCase ()

デフォルト・ロケールのルールを使って、このString内のすべての文字を小文字に変換します。

// ※ 環境によって違う場合があります。
System.out.println(Locale.getDefault()); // ja_JP

System.out.println("".toLowerCase()); // ""
System.out.println("abcdef".toLowerCase()); // "abcdef"
System.out.println("ABCDEF".toLowerCase()); // "abcdef"
System.out.println("あいうえお".toLowerCase()); // "あいうえお"
System.out.println("ΙΧΘΥΣ".toLowerCase()); // "ιχθυς"

String toLowerCase (Locale locale)

指定されたLocaleのルールを使って、このString内のすべての文字を小文字に変換します。

final var s1 = "I"; // アルファベットのI (u0049)
final var s2 = "İ"; // トルコ語のI (u0130)

{
    // 英語
    final var en = Locale.ENGLISH;

    final var ret1 = s1.toLowerCase(en);
    System.out.println(ret1); // "i"
    System.out.println(ret1.codePoints().mapToObj(Integer::toHexString).toList()); // [69]

    final var ret2 = s2.toLowerCase(en);
    System.out.println(ret2); // "i̇ "
    System.out.println(ret2.codePoints().mapToObj(Integer::toHexString).toList()); // [69, 307]
}

{
    // トルコ語
    final var tr = new Locale("tr");

    final var ret1 = s1.toLowerCase(tr);
    System.out.println(ret1); // "ı"
    System.out.println(ret1.codePoints().mapToObj(Integer::toHexString).toList()); // [131]

    final var ret2 = s2.toLowerCase(tr);
    System.out.println(ret2); // "i"
    System.out.println(ret2.codePoints().mapToObj(Integer::toHexString).toList()); // [69]
}

String toString ()

このオブジェクト(これはすでに文字列です!)

final var ret1 = "abcd".toString();
System.out.println(ret1); // "abcd"

final var ret2 = "あいうえお".toString();
System.out.println(ret2); // "あいうえお"

String toUpperCase ()

デフォルト・ロケールのルールを使って、このString内のすべての文字を大文字に変換します。

// ※ 環境によって違う場合があります。
System.out.println(Locale.getDefault()); // ja_JP

System.out.println("".toUpperCase()); // ""
System.out.println("abcdef".toUpperCase()); // "ABCDEF"
System.out.println("ABCDEF".toUpperCase()); // "ABCDEF"
System.out.println("あいうえお".toUpperCase()); // "あいうえお"
System.out.println("ιχθυς".toUpperCase()); // "ΙΧΘΥΣ"

String toUpperCase (Locale locale)

指定されたLocaleのルールを使って、このString内のすべての文字を大文字に変換します。

final var s1 = "i"; // アルファベットのi (u0069)
final var s2 = "ı"; // トルコ語のı (u0130)

{
    // 英語
    final var en = Locale.ENGLISH;

    final var ret1 = s1.toUpperCase(en);
    System.out.println(ret1); // "I"
    System.out.println(ret1.codePoints().mapToObj(Integer::toHexString).toList()); // [49]

    final var ret2 = s2.toUpperCase(en);
    System.out.println(ret2); // "I"
    System.out.println(ret2.codePoints().mapToObj(Integer::toHexString).toList()); // [49]
}

{
    // トルコ語
    final var tr = new Locale("tr");

    final var ret1 = s1.toUpperCase(tr);
    System.out.println(ret1); // "İ"
    System.out.println(ret1.codePoints().mapToObj(Integer::toHexString).toList()); // [130]

    final var ret2 = s2.toUpperCase(tr);
    System.out.println(ret2); // "I"
    System.out.println(ret2.codePoints().mapToObj(Integer::toHexString).toList()); // [49]
}

<R> R transform (Function<? super String,? extends R> f)

このメソッドは、関数をthis文字列に適用します。

final var s = "1234";

// int に変換して2倍した結果を返す。
final var ret = s.transform(v -> Integer.parseInt(v) * 2);
System.out.println(ret); // 2468
final var s = "a";

final var ret = s.transform(v -> v.repeat(5).toUpperCase());
System.out.println(ret); // "AAAAA"

String translateEscapes ()

文字列リテラルのように変換されたエスケープ・シーケンスを使用して、値がこの文字列の文字列を返します。

// "\\n"でエスケープシーケンスではなく通常の文字列としています。
final var s = "aaaa\\nBBBB";

System.out.println(s); // "aaaa\nBBBB"

// """
// aaaa
// BBBB
// """
System.out.println(s.translateEscapes());

String trim ()

値がこの文字列で、先頭と末尾のすべてのスペースが削除され、コード・ポイントが'U+0020' (空白文字)以下の文字でスペースが定義されている文字列を返します。

関連メソッド:strip()

// 先頭と末尾に半角スペース
final var ret = " abcd ".trim();
System.out.println(ret.trim()); // "abcd"
// 先頭と末尾に全角スペース
final var ret = " あいうえお ".trim();
System.out.println(ret); // " あいうえお "
// 空白・タブ・改行・"ABC"・空白・タブ・改行
final var s = " \t\nABC \t\n";

// ※見やすさのために、空白は*、タブは\t、改行は\nとして出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*")
        .replace("\t", "\\t")
        .replace("\n", "\\n");

// "*\t\nABC*\t\n"
System.out.println(func.apply(s));

final var ret = s.trim();

// "ABC"
System.out.println(ret);
final var s = "  <html>\n" +
        "    <body>\n" +
        "      <p>Hello</p>\n" +
        "    </body>\n" +
        "  </html>  ";

// ※見やすさのために、空白は*として出力します。
final Function<String, String> func = (v) -> v.replace(" ", "*");

// """
// **<html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>**
// """
System.out.println(func.apply(s));

final var ret = s.trim();

// """
// <html>
// ****<body>
// ******<p>Hello</p>
// ****</body>
// **</html>
// """
System.out.println(func.apply(ret));

static String valueOf (boolean b)

boolean引数の文字列表現を返します。

final var ret1 = String.valueOf(true);
System.out.println(ret1); // "true"

final var ret2 = String.valueOf(false);
System.out.println(ret2); // "false"

static String valueOf (char c)

char引数の文字列表現を返します。

final var ret1 = String.valueOf('a');
System.out.println(ret1); // "a"

final var ret2 = String.valueOf('あ');
System.out.println(ret2); // "あ"

static String valueOf (char[] data)

char配列引数の文字列表現を返します。

final char[] data = {'b', 'o', 'o', 'k'};

final var ret = String.valueOf(data);
System.out.println(ret); // "book"
final char[] data = {'あ', 'い', 'う', 'え', 'お'};

final var ret = String.valueOf(data);
System.out.println(ret); // "あいうえお"

static String valueOf (char[] data, int offset, int count)

char配列引数の特定の部分配列の文字列表現を返します。

final char[] data = {'b', 'o', 'o', 'k'};

System.out.println(String.valueOf(data, 0, 1)); // "b"
System.out.println(String.valueOf(data, 0, 2)); // "bo"
System.out.println(String.valueOf(data, 0, 3)); // "boo"
System.out.println(String.valueOf(data, 0, 4)); // "book"

System.out.println(String.valueOf(data, 1, 3)); // "ook"
System.out.println(String.valueOf(data, 2, 2)); // "ok"
System.out.println(String.valueOf(data, 3, 1)); // "k"

static String valueOf (double d)

double引数の文字列表現を返します。

final double d1 = 1.0;
final double d2 = 0.12345;
final double d3 = 1.23e10;

System.out.println(String.valueOf(d1)); // "1.0"
System.out.println(String.valueOf(d2)); // "0.12345"
System.out.println(String.valueOf(d3)); // "1.23E10"

static String valueOf (float f)

float引数の文字列表現を返します。

final float f1 = 1.0f;
final float f2 = 0.12345f;
final float f3 = 1.23e10f;

System.out.println(String.valueOf(f1)); // "1.0"
System.out.println(String.valueOf(f2)); // "0.12345"
System.out.println(String.valueOf(f3)); // "1.23E10"

static String valueOf (int i)

int引数の文字列表現を返します。

final int i1 = 0;
final int i2 = 1234;
final int i3 = -5678;

System.out.println(String.valueOf(i1)); // "0"
System.out.println(String.valueOf(i2)); // "1234"
System.out.println(String.valueOf(i3)); // "-5678"

static String valueOf (long l)

long引数の文字列表現を返します。

final long l1 = 0L;
final long l2 = 1234567890123456789L;
final long l3 = -5678901234L;

System.out.println(String.valueOf(l1)); // "0"
System.out.println(String.valueOf(l2)); // "1234567890123456789"
System.out.println(String.valueOf(l3)); // "-5678901234"

static String valueOf (Object obj)

Object引数の文字列表現を返します。

final var obj = LocalDate.of(2021, 3, 11);

final var ret = String.valueOf(obj);
System.out.println(ret); // "2021-03-11"
final var obj = new URL("https://example.com/");

final var ret = String.valueOf(obj);
System.out.println(ret); // "https://example.com/"

関連記事

ページの先頭へ