如何用空格替换所有带空格的逗号只能在字符串中?

问题描述 投票:-4回答:3

我有的是:

"atul ,   singh Java   ,  computer science and engineering     ,    Data structures &   algorithms" 

我想要的是:

"atul,singh Java,computer science and engineering,Data structures &   algorithms"

任何人都可以告诉我该怎么做?

java regex string
3个回答
3
投票

你可以使用这个正则表达式:

\s*,\s*

在java中:

your_string= your_string.replaceAll("\\s*,\\s*", ",");

说明:

  • \s* - 匹配一串都是“空格”的字符(空格,制表符,换行符等)
  • , - 匹配角色“,”

2
投票

接受你的意见。

使用.split("\\s+,\\s+")取出逗号和周围的whitespacing。如果逗号两边都没有空格,请将+替换为*

将该字符串数组与逗号连接在一起,没有空格


0
投票

试试这个

String a= " atul ,  singh Java , computer science and engineering , Data structures & algorithms ";
String b[]= a.split(",");
String c = "";
for(int i=0;i<b.length;i++){
  c+=b[i].trim()+",";
}
System.out.println(c.substring(0,c.length()-1));
}
© www.soinside.com 2019 - 2024. All rights reserved.