如何解决用另一个字符串中的另一个字符替换字符串中的一个字符
我试图最终用另一组字符串替换一个句子。但是我在尝试用另一个字符串的另一个字符替换字符串中的字符时遇到了障碍。
这是我目前所拥有的。
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);
这种替换字符的方法不起作用。有人可以帮我吗?
解决方法
原因
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();
,
我将按如下方式使用字符数组。对字符数组进行更改,然后使用 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!
,
您可以使用 codePoints
方法遍历此字符串的字符并将它们替换为另一个字符串中的字符(如果有)。
addView(child: View?)
MyCustomWrapperBinding
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。