简体   繁体   中英

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 . 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.
  • 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."

It should be transformed to:

"Kaie iks t obere ntue*8"

However, using my code I get: "Katie likes to observe nature*."

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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