0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javaの文字列置換処理まとめ

Posted at

よく使用するJavaでの文字列置換の方法をまとめます。

replace()

文字列⇒文字列の置換。

String str = "今日の天気は晴れです。";
str.replace("晴れ", "雨");
System.out.println(str.replace("晴れ", "雨")); // 今日の天気は雨です。

replaceAll()

正規表現⇒文字列の置換。

String str = "今日の降水確率は30%です。";
String str2 = str.replaceAll("\\d{1,2}", "80");
System.out.println(str2); // 今日の降水確率は80%です。

String.format()

書式文字列を任意の値で置換することができます。
文字列を挿入する時は、「%s」を使用します。

String str = String.format("担当者は%sさん", "鈴木");
// 担当者は鈴木さん

複数の文字列を挿入する場合は、書式文字列の数分の置換後文字列を引数として追加します。

String str = String.format("%sさんは%s出身", "鈴木", "静岡県");
// 鈴木さんは静岡県出身

文字列以外にも以下のような書式を指定することができます。

書式文字列

  • %s: 文字列を挿入
  • %d: 整数を挿入
  • %f: 浮動小数点数を挿入
  • %b: 真偽値(true, false)を挿入
  • %c: 1バイト文字を挿入

参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?