スポンサーサイト

  • 2013.11.08 Friday
  • -
  • -
  • -
  • by スポンサードリンク

一定期間更新がないため広告を表示しています


エスケープシーケンス

文字列の中で次のものは特別な意味を持ちます。エスケープシーケンス と呼ばれています。

種別 説明 使用例
¥n 改行コード。 "Hello.¥n"
¥t タブ文字。 "Name:¥tTanaka"
¥¥ バックスラッシュ。 "¥¥"
¥' シングルクォーテーション(') '¥''
¥" ダブルクォーテーション(") "¥""
¥uxxxx Unicode xxxx の文字。 "¥u3042"

文字列を分割する(split)

split(reg) は、正規表現 reg で文字列を分割し、その配列を返します。

String[] strs = "2003/05/19".split("/");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}


指定文字が出現する場所を得る(indexOf)

str.indexOf(ch) は、文字列の中で文字 ch が最初に出現する位置を、0を基点とする文字数で返します。見つからない時は -1 を返します。

String str = "ABCDEFG";
System.out.println(str.indexOf('C'));

文字の代わりに文字列を指定することもできます。

String str = "ABCDEFG";
System.out.println(str.indexOf("DEF"));

第2引数 n を指定すると、n番目以降の場所から探します。

String str = "ABCABCABC";
System.out.println(str.indexOf('A', 2));

lastIndexOf(ch) は、文字列の後ろから探します。

String str = "ABCABCABC";
System.out.println(str.lastIndexOf('A'));


n番目の文字を得る(charAt)

charAt(n) は、0を基点として n番目の文字を返します。

String str = "ABCDEFG";
System.out.println(str.charAt(2));


文字列を大小比較する(compareTo, compareToIgnoreCase)

compareTo(str) は、文字列が、str と比べて辞書的にどちらが大きいか調べます。str のほうが大きい時は負の値を、等しい時は 0を、小さい時は正の値を返します。

String str = "ABC";
if (str.compareTo("ABC") == 0) { ... }

大文字・小文字を無視して比較する場合は compareToIgnoreCase(str) を用います。

String str = "ABC";
if (str.compareToIgnoreCase("abc") == 0) { ... }


等しいかどうか調べる(equals, equalsIgnoreCase)

equals(str) は、文字列が str と等しいかどうかを調べます。

String str = "ABC";
if (str.equals("ABC")) { ... }

大文字・小文字を無視して比較する場合は equalsIgnoreCase(str) を用います。

String str = "ABC";
if (str.equals("abc")) { ... }

文字列を比較する際に、== 演算子を用いてはなりません。strA == strB は、strA と strB が同じオブジェクトかどうかを調べたりする際に用いる演算子です。例えば、下記の例では、strA も strB も文字列の値は "ABCDEF" のはずですが、演算結果は false になります。

String strA = "ABC";
String strB = "ABC";
strA = strA + "DEF";
strB = strB + "DEF";
if (strA == strB) {
System.out.println("true");
} else {
System.out.println("false");
}


文字列長を得る(length)

length() は、文字列の長さを返します。Java では Unicode を基本とするため、日本語のような全角文字も 1文字として数えます。

String str = "ABCDEFG";
System.out.println(str.length());


文字列(String)

文字列 を扱うには、String を用います。

String str = "abc";