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

我被要求编写一个使用特定规则对给定句子进行编码的类。此类应使用循环和Stringbuffer。规则是:


每个点“。” 用“ *”代替。

每个第3个字符(如果此字符不是空格或点)都应删除。

在新句子的末尾添加一个数字,表示已消除字符的总数。

我已经编写了代码,但是我无法理解为什么它不起作用。有人可以帮忙吗?


例如:


句子=“ Katie喜欢观察自然。”


应将其转换为:


“ Kaie iks t obere ntue * 8”


但是,使用我的代码,我得到:“ Katie喜欢观察自然*。”


谢谢!


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();


}


GCT1015
浏览 196回答 1
1回答

江户川乱折腾

逻辑的主要问题是,在将字符串附加到字符串之后,buff您可以继续进行该迭代,而不是跳转到字符串中的下一个字符。将您的方法更改为如下:public static StringBuffer createEncodedSentence(String sentence) {&nbsp; &nbsp; StringBuffer buff = new StringBuffer();&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; char a;&nbsp; &nbsp; for (int i = 0; i < sentence.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; a = sentence.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; if (a == '.') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; buff.append("*");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if ((i + 1) % 3 == 0 && a != ' ' && a != '.') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; buff.append(sentence.charAt(i));&nbsp; &nbsp; }&nbsp; &nbsp; buff.append(counter);&nbsp; &nbsp; return buff;}逻辑:如果字符是a,.则我们附加a*并跳转到句子中的下一个字符。如果它是第三个索引,则我们增加计数器并跳到下一个字符。在for循环迭代的最后,我们添加已替换的字符数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java