Garry Steve
Garry Steve

Reputation: 129

Java - replace comma alternatively

I have a String which contains data separated by comma (,) for each value. I wanna replace comma by some other delimiter. But need to replace comma alternatively.
That means second, forth, sixth occurrence of comma need to be replaced. Is there any possible way to do?

Eg: "a,b,c,d,e,f" is the string available and want the output as "a,b c,d e,f".

Upvotes: 2

Views: 799

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

You can use some regex with replaceAll like this :

String str = "a,b,c,d,e,f";
String delimiter = " ";//You can use any delimiter i use space in your case
str = str.replaceAll("([a-zA-Z]+,[a-zA-Z]+)(,)", "$1" + delimiter);

System.out.println(str);

result

a,b c,d e,f

regex demo

Upvotes: 4

NAK
NAK

Reputation: 458

Here is a simple code that uses array of characters to do the task.

    public class ReplaceAlternateCommas {

    public static void main(String[] args) {
                String str = "a,bg,dfg,d,v";
                System.out.println(str);
                char[] charArray = str.toCharArray();
                int commaCount=0;
                char replacementChar = ' ';//replace comma with this character
                for(int i=0;i<charArray.length;i++){
                    char ch = charArray[i];
                    if(ch==','){
                        commaCount++;
                        if(commaCount%2==0){
                            charArray[i]=replacementChar;
                        }
                    }
                }
                str = new String(charArray);
                System.out.println(str);
    }
}

If you dont want to use character array you can use regex or StringBuilder .

Upvotes: 2

Related Questions