用另一个字符串中的另一个字符替换字符串中的字符 [英] Replacing a character in a string with another character from another string
问题描述
我试图最终用另一组String替换一个句子.但是我在尝试用另一个String的另一个字符替换String中的char时遇到了障碍.
I am trying to eventually replace a sentence with another set of String. But I hit a roadblock while trying to replace a char in a String with another character of another String.
这是我到目前为止所拥有的.
Here's what I have so far.
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);
这种替换字符的方法不起作用.有人可以帮我吗?
This way of replacing characters doesn't work. Can someone help me?
推荐答案
原因
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
不起作用是因为 String
是不可变的(即,它们永远不变).因此, sentence.replace(...)
实际上并没有改变 sentence
;而是返回新的 String
.您可能需要编写 sentence =句子.replace(...)
才能将结果捕获回 sentence
.
doesn't work is that String
s are immutable (i.e., they never change).
So, sentence.replace(...)
doesn't actually change sentence
; rather, it returns a new String
. You would need to write sentence = sentence.replace(...)
to capture that result back in sentence
.
好的,字符串101:类已关闭(;->).
OK, Strings 101: class dismissed (;->).
现在,尽管如此,您确实不想继续将部分编码的句子
重新分配给自己,因为您几乎可以肯定会发现自己重新编码了您已经编码的句子
.最好保留 sentence
的原始形式,同时一次将编码的字符串建立一个字符,如下所示:
Now with all that said, you really don't want want to keep reassigning your partially encoded sentence
back to itself, because you will, almost certainly, find yourself re-encoding characters of sentence
that you already encoded. Best to leave sentence
in its original form while building up the encoded string one character at a time like this:
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();
这篇关于用另一个字符串中的另一个字符替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!