我有一个这样的字符串:
mysz = "name=john age=13 year=2001";
我想删除字符串中的空格。我尝试了trim(),但这只删除了整个字符串前后的空格。我还尝试了replaceAll(“\\W”,“”),但随后=也被删除。
如何通过以下方式实现字符串:
mysz2 = "name=johnage=13year=2001"
我有一个这样的字符串:
mysz = "name=john age=13 year=2001";
我想删除字符串中的空格。我尝试了trim(),但这只删除了整个字符串前后的空格。我还尝试了replaceAll(“\\W”,“”),但随后=也被删除。
如何通过以下方式实现字符串:
mysz2 = "name=johnage=13year=2001"
当前回答
使用Pattern And Matcher,它更具动态性。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingSpace {
/**
* @param args
* Removing Space Using Matcher
*/
public static void main(String[] args) {
String str= "jld fdkjg jfdg ";
String pattern="[\\s]";
String replace="";
Pattern p= Pattern.compile(pattern);
Matcher m=p.matcher(str);
str=m.replaceAll(replace);
System.out.println(str);
}
}
其他回答
如果您也需要删除不可破坏的空格,可以这样升级代码:
st.replaceAll("[\\s|\\u00A0]+", "");
将每组文本分隔成自己的子字符串,然后连接这些子字符串:
public Address(String street, String city, String state, String zip ) {
this.street = street;
this.city = city;
// Now checking to make sure that state has no spaces...
int position = state.indexOf(" ");
if(position >=0) {
//now putting state back together if it has spaces...
state = state.substring(0, position) + state.substring(position + 1);
}
}
String a="string with multi spaces ";
//or this
String b= a.replaceAll("\\s+"," ");
String c= a.replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ");
//任何空间都可以使用*别忘了sting b中的空格
replaceAll(“\\s”,“”)如何。请参阅此处。
st.replaceAll(“\\s+”,“”)删除所有空格和不可见字符(例如,tab,\n)。
st.replaceAll(“\\s+”,“”)和st.replaceAll(“\\s”,“)产生相同的结果。
第二个正则表达式比第一个正则表达式快20%,但随着连续空格数的增加,第一个正则正则表达式的性能比第二个更好。
如果不直接使用,则将值分配给变量:
st = st.replaceAll("\\s+","")