Emily
Emily

Reputation: 531

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]",""); 

Upvotes: 3

Views: 106

Answers (2)

Justin Jones
Justin Jones

Reputation: 81

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

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174874

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

Upvotes: 6

Related Questions