I need to replace every comma in a string to new line with number in it.
String str = "Peter, Bob, Chester, Mike";
I have done for replacing comma with new line.
str = str.replace(",", "\n");
This give me output like this
Peter
Bob
Chester
Mike
What I’m wanted to do is
1. Peter
2. Bob
3. Chester
4. Mike
*The requirement need string not a array.
>Solution :
you can use the split (which splits the String into a string array) method like so and use a forEach loop:
int counter=0;
for(String s:str.split(",")){
System.out.println(counter+". "+s);
counter++;
}
Hope it helps.