简体   繁体   中英

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,bc,de,f" .

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

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 .

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