java 在java中用换行符替换逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25487146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace comma with newline in java
提问by helloworld
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?
此方法用空格替换所有逗号。谁能指出我哪里出错了?
回答by Darshan Lila
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:
希望能帮助到你:
回答by Donal
String emails = emailList.replaceAll(",", "\n");
回答by qbit
you can use Scanner
too
您可以使用Scanner
太
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:
System.out.println(emailsNew);
将打印:
AA
BB
CC