我的要求是用换行符替换字符串中的所有逗号。
示例:
AA,BB,CC
应表示为
AA
BB
CC
这是我用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;
}
此方法用空格替换所有逗号。 任何人都可以指出我哪里出错了?
答案 0 :(得分:18)
只需使用以下代码:
String emailList="AA,BB,CC";
emailList=emailList.replaceAll(",", "\n");
System.out.println(emailList);
<强>输出强>
AA
BB
CC
现在基于您的代码,您的方法如下所示:
public String getFormattedEmails(String emailList) {
String emails=emailList.replaceAll(",", "\n");
return emails;
}
希望有所帮助:
答案 1 :(得分:4)
String emails = emailList.replaceAll(",", "\n");
答案 2 :(得分:1)
您也可以使用Scanner
String emails = "AA,BB,CC"
String emailsNew = replaceCommas(emails);
String replaceCommas(String a){
String result = "";
Scanner scan = new Scanner(a);
scan.useDelimiter(",");
while(scan.hasNext()){
result += scan.next() + "\n";
}
return result;
}
System.out.println(emailsNew);
将打印:
AA
BB
CC