[英]How do I replace nth character in a String with a new character?
I have been asked to write a class that encodes a given sentence using specific rules. 我被要求编写一个使用特定规则对给定句子进行编码的类。 This class should use loops and
Stringbuffer
. 此类应使用循环和
Stringbuffer
。 The rules are: 规则是:
I have written the code, but I am not able to understand why it is not working. 我已经编写了代码,但是我无法理解为什么它不起作用。 Can anyone help?
有人可以帮忙吗?
For example: 例如:
sentence = "Katie likes to observe nature."
句子=“ Katie喜欢观察自然。”
It should be transformed to: 它应该转换为:
"Kaie iks t obere ntue*8"
“ Kaie iks t obere ntue * 8”
However, using my code I get: "Katie likes to observe nature*." 但是,使用我的代码,我得到:“ Katie喜欢观察自然*。”
Thank you! 谢谢!
public void createEncodedSentence() {
StringBuffer buff = new StringBuffer();
int counter = 0;
char a;
for (int i = 0; i < sentence.length(); i++) {
a = sentence.charAt(i);
if (a == '.') {
buff.append('*');
}
if (a != ' ' && a != '.') {
counter++;
}
if (counter % 3 == 0) {
buff.append("");
}
buff.append(sentence.charAt(i));
}
encodedSentence = buff.toString();
}
The main issue with your logic is that after you append a String to buff
you continue with that iteration instead of jumping to the next character in the String. 逻辑的主要问题是,在将字符串附加到
buff
之后,您将继续该迭代,而不是跳转到字符串中的下一个字符。
Change your method to as follows : 将您的方法更改为如下:
public static StringBuffer createEncodedSentence(String sentence) {
StringBuffer buff = new StringBuffer();
int counter = 0;
char a;
for (int i = 0; i < sentence.length(); i++) {
a = sentence.charAt(i);
if (a == '.') {
buff.append("*");
continue;
}
if ((i + 1) % 3 == 0 && a != ' ' && a != '.') {
counter++;
continue;
}
buff.append(sentence.charAt(i));
}
buff.append(counter);
return buff;
}
Logic: 逻辑:
.
.
then we append a *
and jump to the next character in the sentence. *
并跳到句子中的下一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.