2

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".

2
  • indexOf, a counter, and the replace method. throw in a simple loop and we're there. Commented Oct 30, 2017 at 7:48
  • 1
    Use an if condition to select the relevant occurrences. Commented Oct 30, 2017 at 7:49

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the help. For me using regex will be more efficient. But coming to actual scenario I have words instead of characters which I mentioned earlier in the sample. Can you please tell me how to make this work for the words instead of characters.
@Sai do you know what \w can match?
is matching only a single character ... But I need to match a entire word.
But it is not working if the string is of form ABC,CDA,hfhd,hdhdhdj,ejdjdj,xxxx
@Sai if your words can contains only upper and lower characters you can use ([a-zA-Z]+,[a-zA-Z]+)(,) check the demo here hope this can help you
|
2

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 .

1 Comment

Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.