这个问题在这里已经有答案了
:
Java字符串未转换为小写[重复]
(2个答案)
Java String.replace/replaceAll不起作用
(4个答案)
字符串替换方法没有替换字符
(5个答案)
如何替换字符串的子字符串[重复]
(7个答案)
8小时前就关门了。
我有一个由6个不同字符串组成的数组。现在,我专注于用不同的字符替换数组第一句话中的所有字母。例如,句子中的所有“r”将变为“i”,所有“t”将变为“u”。我在下面尝试的代码只替换了我在最后一行中编写的代码的字符。(它将所有的“p”替换为“u”,但忽略上面的所有代码)
如何替换句子中的每个字符?
public static void replaceString(String[] arr) {
String s1 = arr[0];
for (String i: arr) {
String sentence1 = s1.toLowerCase().replace("a", "t");
sentence1 = s1.toLowerCase().replace("r", "m");
sentence1 = s1.toLowerCase().replace("e", "i");
sentence1 = s1.toLowerCase().replace("s", "n");
sentence1 = s1.toLowerCase().replace("p", "u");
System.out.println(sentence1);
}
}发布于 2021-03-02 06:38:27
你需要重用返回的字符串,否则你总是重写整个
..。记住,字符串是不可变的。
String sentence1 = s1.toLowerCase().replace("a", "t");
sentence1 = sentence1.toLowerCase().replace("r", "m");
sentence1 = sentence1.toLowerCase().replace("e", "i");
sentence1 = sentence1.toLowerCase().replace("s", "n");
sentence1 = sentence1.toLowerCase().replace("p", "u");..。可以重写为:
String sentence1 = s1.toLowerCase()
.replace("a", "t")
.replace("r", "m");
.replace("e", "I");
.replace("s", "n");
.replace("p", "u");发布于 2021-03-02 06:42:10
你可能会发现
更好的方法:
sentence1 = StringUtils.replaceChars(s1.toLowerCase(), "aresp", "tminu");添加Apache的
commons-lang3
库作为依赖项。
发布于 2021-03-02 06:43:03
S是不可变的。你不能就地修改它们,你总是必须创建一个新的对象。
示例:
String s1 = "";
String s2 = s1 + "foo";
String s3 = s2.replace("foo", "bar");和
不会改变,因为他们永远不会被重新分配。尽管这些变量的值保持不变:
System.out.println(s1); // ""
System.out.println(s2); // "foo"
System.out.println(s3); // "bar"如果你想
要进行更改,您需要为其重新分配新值:
String s1 = "";
s1 = s1 + "foo";
s1 = s1.replace("foo", "bar");现在s1将成为
https://stackoverflow.com/questions/66430696
复制相似问题