简体   繁体   中英

How to replace the n th occurance of a character in a String ?

I need to replace all commas after the 5th one. So if a String contains 10 commans, I want to leave only the first 5, and remove all subsequent commas.

How can I do this ?

String sentence = "Test,test,test,test,test,test,test,test"; 
String newSentence = sentence.replaceAll(",[6]",""); 

Just capture all the characters from the start upto the 5th comma and match all the remaining commas using the alternation operator | . So , after | should match all the remaining commas. By replacing all the matched chars with $1 will give you the desired output.

sentence.replaceAll("^((?:[^,]*,){5})|,", "$1");

DEMO

In case you were wondering how to solve this problem without using regular expressions... There are libraries that could make your life easier but here is the first thought that came to mind.

public String replaceSpecificCharAfter( String input, char find, int deleteAfter){

    char[] inputArray = input.toCharArray();
    String output = ""; 
    int count = 0;

    for(int i=0; i <inputArray.length; i++){
        char letter = inputArray[i];
        if(letter == find){
            count++;
            if (count <= deleteAfter){
                 output += letter;
            }
         }
         else{
             output += letter;
         }
    }

    return output;
}

Then you would invoke the function like so:

String sentence = "Test,test,test,test,test,test,test,test"; 
String newSentence = replaceSpecificCharAfter(sentence, ',', 6);

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