String.substring
私はそのインデックスで aが機能するはずだと簡単に思いますString.replace
。
インデックスの 1 つのコードは次のとおりです - [2, 4]
: -
String str = "I am a girl and I live in Nepal.";
String str2 = str.replace(str.substring(2, 4), "{" + str.substring(2, 4) + "}");
System.out.println(str2); // str is not changed.
出力: -
I {am} a girl and I live in Nepal.
そのインデックスがわからず、単語しかない場合は、String.indexOf
メソッドを使用してそれを見つけることができます。
これがより良い解決策です: -
String str = "I am a girl and I live in Nepal.";
int startIndex = str.indexOf("am");
int endIndex = startIndex + "am".length();
str = str.replace(str.substring(startIndex, endIndex),
"{" + str.substring(startIndex, endIndex) + "}");
System.out.println(str);