Java 文字列

文字列はテキストの保存に使用されます。

String 変数には、二重引用符で囲まれた文字のコレクションが含まれます。

String 型の変数を作成し、値を割り当てます。


String greeting = "Hello";
System.out.println(greeting);

結果

Hello

文字列の長さ

Java の String は実際にはオブジェクトであり、文字列に対して特定の操作を実行できるメソッドが含まれています。 たとえば、文字列の長さは length() メソッドで確認できます。

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());

結果

The length of the txt string is: 26
 

その他の文字列メソッド

toUpperCase()toLowerCase() など、多くの文字列メソッドが使用できます。

String txt = "Hello World";
System.out.println(txt.toUpperCase());   // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase());   // Outputs "hello world"

結果

HELLO WORLD
hello world

文字列内の文字の検索

indexOf() メソッドは、文字列 (空白を含む) 内で指定されたテキストが最初に出現するインデックス (位置) を返します。 ):

String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7

結果

7

Java はゼロから位置を数えます。
0 は文字列の最初の位置、1 は 2 番目、2 は 3 番目です...

文字列の連結

+ 演算子を文字列の間に使用して、文字列を結合できます。 これは連結と呼ばれます:

String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);

結果

John Doe

印刷時に firstName と lastName の間にスペースを作成するために空のテキスト (" ") を追加していることに注意してください。

concat() メソッドを使用して 2 つの文字列を連結することもできます。

String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));

結果

John Doe

数値と文字列の追加

警告!

Java は、加算と連結の両方に + 演算子を使用します。

数字が追加されます。 文字列は連結されます。

2 つの数値を加算すると、結果は数値になります:

int x = 10;
int y = 20;
int z = x + y;  // z は 30 (整数/数値) になります。
System.out.println(z);

結果

30

2 つの文字列を追加すると、結果は文字列の連結になります。

String x = "10";
String y = "20";
String z = x + y;  //z は 1020 (文字列) になります。

結果

1020

数値と文字列を追加すると、結果は文字列の連結になります。

String x = "10";
int y = 20;
String z = x + y;  // z は 1020 (文字列) になります。

結果

1020

文字列 - 特殊文字

文字列は引用符で囲む必要があるため、Java はこの文字列を誤解します。 エラーが生成されます:

String txt = "We are the so-called "Vikings" from the north.";

この問題を回避する解決策は、バックスラッシュ エスケープ文字を使用することです。

バックスラッシュ (\) エスケープ文字は、特殊文字を文字列文字に変換します。

エスケープ文字 結果 説明
\' ' 一重引用符
\" " 二重引用符
\\ \ バックスラッシュ

シーケンス \"  は文字列に二重引用符を挿入します。

 

String txt = "We are the so-called \"Vikings\" from the north.";
System.out.println(txt);

結果

We are the so-called "Vikings" from the north.

シーケンス \'  文字列に一重引用符を挿入します:

 

String txt = "It\'s alright.";

結果

It's alright.

シーケンス \\  文字列に単一のバックスラッシュを挿入します:

 

String txt = "The character \\ is called backslash.";

結果

The character \ is called backslash.

Java で有効なその他の一般的なエスケープ シーケンスは次のとおりです。

コード 説明する 結果
\n New Line String txt = "Hello\nWorld!";
Hello
World!
\r Carriage Return String txt = "Hello\rWorld!";
Hello
World!
\t Tab String txt = "Hello\tWorld!";
Hello World!
\b Backspace String txt = "Hel\blo World!";
Helo World!
\f Form Feed