Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace comma with New line number in Java?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading