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?
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.
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.
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:
String emails = emailList.replaceAll(",", "\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With