Replace comma with new line in java

My requirement is to replace all the commas in the line with a new line.

Example:

AA,BB,CC 

should represent how

 AA BB CC 

here is my implementation for replacing commas with a new line,

 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 someone point me where i was wrong?

+6
source share
3 answers

Just use the following code:

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

Output

 AA BB CC 

Now, based on your code, your method looks like this:

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

Hope this helps:

+18
source
 String emails = emailList.replaceAll(",", "\n"); 
+4
source

You can use Scanner too

 String emails = "AA,BB,CC" String emailsNew = replaceCommas(emails); String replaceCommas(String a){ StringBuilder result = new StringBuilder(); Scanner scan = new Scanner(a); scan.useDelimiter(","); while(scan.hasNext()){ result.append(scan.next()); result.append("\n"); } return result.toString(); } 

System.out.println(emailsNew); will print:

 AA BB CC 
+1
source

Source: https://habr.com/ru/post/974307/


All Articles