LoginSignup
1
1

replaceメソッド

Posted at

replaceメソッド

文字列内の指定した文字列や文字を別の文字列や文字に置換するためのメソッド

public String replace(CharSequence target, CharSequence replacement)

パラメータ

  • target : 置換したい文字列や文字のシーケンス
  • replacement : 置換する文字列や文字のシーケンス

戻り値

置換後の文字列が返される

String str = "Hello, World!";
String newStr = str.replace("Hello", "Hi");
System.out.println(newStr); // 出力: "Hi, World!"

元の文字列(str)の中から "Hello" という部分を "Hi" に置換

replaceメソッドは新しい文字列を返す
→置換後の文字列を newStr に代入している

replace メソッドの注意点

元の文字列自体を変更するのではなく、置換後の新しい文字列を生成
→元の文字列には影響なし

今回は、targetパラメータに文字列や文字のシーケンスを指定したが、正規表現を使用して複雑なパターンの置換もできる

  • replaceメソッドは大文字と小文字を区別する
    置換対象の文字列や文字の大文字と小文字に注意する必要がある
1
1
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
1