简体   繁体   中英

Removing every 5th char in a string and return new String

I'm trying to eliminate every 5th character of a string, unless the character is a space or a dot, and return the new string.

At the minute I can only seem to return the characters at every fifth occurrence but not manipulate them and return the new string.

Example Original String: "James scored 1 goal. His team won."

New String: "Jame scoed 1 goal! His team won!"

I've tried to use a for loop with a selection statement but can't seem to manipulate correctly and then return the full new string.

public class TextProcessorTest{
    public static void main(String args[]) {
        String sentence = "James scored 1 goal. His team won.";
        String newSentence;
        StringBuffer buff = new StringBuffer();
        int len = sentence.length();

        for(int i=4;i<len;i=i+5){
            char c = sentence.charAt(i);
            System.out.print(c);

            if(c == ' '){
                buff.append(c);
            }else if(c == '.'){
                buff.append(c);
            }else{
                buff.append("");
            }
        }

        newSentence = buff.toString();
        System.out.println(newSentence);
    }
}

Expected result is: "Jame scoed 1 goal! His team won!"

Actual result is: "sr . . "

This is pretty simple. Just ignore every 5th character and build new string using StringBuilder :

public static String remove(String str) {
    StringBuilder buf = new StringBuilder(str.length());

    for (int i = 1; i <= str.length(); i++)
        if (str.charAt(i - 1) == ' ' || str.charAt(i - 1) == '.' || i % 5 != 0)
            buf.append(str.charAt(i - 1));

    return buf.toString();
}

StringBuilder vs StringBuffer

  • StringBuffer use in concurrent modification. This is thread-safe .
  • StringBuilder use in all not concurrent modifications.

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