简体   繁体   English

如何用新字符替换字符串中的第n个字符?

[英]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: 规则是:

  • Each dot '.' 每个点“。” is to be replaced by '*'. 用“ *”代替。
  • Every 3rd character (if this character is not a space or a dot) should be eliminated. 每个第3个字符(如果此字符不是空格或点)都应删除。
  • Add at the end of the new sentence a number representing total number of eliminated characters. 在新句子的末尾添加一个数字,表示已消除字符的总数。

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: 逻辑:

  • If the character is a . 如果字符. then we append a * and jump to the next character in the sentence. 然后添加*并跳到句子中的下一个字符。
  • If it is the 3rd index then we increment the counter and jump to the next character. 如果它是第三个索引,则我们增加计数器并跳到下一个字符。
  • At the end of the for-loop iteration, we add the number of characters that have been replaced 在for循环迭代的最后,我们添加已替换的字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM