Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace comma with newline in java

Tags:

java

My requirement is to replace all commas in a string with newline.

Example:

AA,BB,CC

should represent as

AA
BB
CC

here's my implementation to replace commas with newline,

public String getFormattedEmails(String emailList) {
    List<String> emailTokens = Arrays.asList(emailList.split(","));
    String emails = "";
    StringBuilder stringBuilder = new StringBuilder();
    String delimiter = "";
    for(String email : emailTokens){
        stringBuilder.append(delimiter);
        stringBuilder.append(email);
        delimiter = "\n";
    }
    emails = stringBuilder.toString();
    return emails;
}

this method replaces all commas with a space. can anyone point me where did I go wrong?

like image 337
helloworld Avatar asked Aug 25 '14 13:08

helloworld


People also ask

How do you replace a character in a new line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you replace new line and space in a string in Java?

In order to replace all line breaks from strings replace() function can be used. String replace(): This method returns a new String object that contains the same sequence of characters as the original string, but with a given character replaced by another given character.


2 Answers

Simply use following code:

String emailList="AA,BB,CC";
emailList=emailList.replaceAll(",", "\n");
System.out.println(emailList);

Output

AA
BB
CC

Now based on above your code, your method looks like following:

public String getFormattedEmails(String emailList) {
String emails=emailList.replaceAll(",", "\n");
return emails;
}

Hope it helps:

like image 94
Darshan Lila Avatar answered Sep 28 '22 17:09

Darshan Lila


String emails = emailList.replaceAll(",", "\n");
like image 20
Donal Avatar answered Sep 28 '22 16:09

Donal