最后,我试图用另一组字符串替换一个句子。但是,当我试图用另一个字符串的另一个字符替换字符串中的字符时,我遇到了一个路障。
到目前为止我的情况是这样的。
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";
//swapping each char of 'sentence' with the chars in 'encode'
for (int i = 0; i < sentence.length(); i++) {
int indexForEncode = letters.indexOf(sentence.charAt(i));
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
}
System.out.println(sentence);
这种替换字符的方法不起作用。有人能帮我吗?
发布于 2021-03-17 17:39:42
原因
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
不起作用的是String
是不变的(也就是说,它们永远不会改变)。因此,sentence.replace(...)
实际上并不改变sentence
,而是返回一个新的String
。您需要编写sentence = sentence.replace(...)
才能在sentence
中捕获该结果。
好的,字符串101:下课(;->)
现在,尽管如此,您确实不想继续将部分编码的sentence
重新分配回自己,因为几乎可以肯定,您会发现自己重新编码了已经编码的sentence
的字符。最好是保留sentence
的原始形式,同时每次构建一个编码的字符串,如下所示:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sentence.length(); i++){
int indexForEncode = letters.indexOf(sentence.charAt(i));
sb.append(indexForEncode != -1
? encode.charAt(indexForEncode)
: sentence.charAt(i)
);
}
sentence = sb.toString();
发布于 2021-03-17 18:02:30
我将使用字符数组,如下所示。对字符数组进行更改,然后使用String.valueOf
获取字符串的新版本。
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";
char[] chars = sentence.toCharArray();
for (int i = 0; i < chars.length; i++){
int indexForEncode = letters.indexOf(sentence.charAt(i));
// if index is < 0, use original character, otherwise, encode.
chars[i] = indexForEncode < 0 ? chars[i] : encode.charAt(indexForEncode);
}
System.out.println(String.valueOf(chars));
打印
xahhi, tbga zi jaaz wiq!
https://stackoverflow.com/questions/66683491
复制相似问题