1. String.trim()
trim()是去掉首尾空格
2.str.replace(" ", ""); 去掉所有空格,包括首尾、中间
代码如下
Stringstr = " hell o ";
String str2 =str.replaceAll(" ", "");
System.out.println(str2);
3.或者replaceAll(" +",""); 去掉所有空格
代码如下
4.str= .replaceAll("s*", "");
可以替换大部分空白字符, 不限于空格
s 可以匹配空格、制表符、换页符等空白字符的其中任意一个
或者下面的代码也可以去掉所有空格,包括首尾、中间
代码如下
publicString remove(String resource,char ch)
{
StringBufferbuffer=new StringBuffer();
int position=0;
charcurrentChar;
while(position<resource.length())
{
currentChar=resource.charAt(position++);
if(currentChar!=ch)buffer.append(currentChar); } return buffer.toString();
}
大家看一下实例
代码如下
importjava.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @authorlei
* 2011-9-2
*/
public class StringUtils {
public static StringreplaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p= Pattern.compile("s*|t|r|n");
Matcher m = p.matcher(str);
dest =m.replaceAll("");
}
return dest;
}
public static void main(String[]args) {
System.out.println(StringUtils.replaceBlank("just doit!"));
}
/*-----------------------------------
笨方法:String s ="你要去除的字符串";
.去除空格:s = s.replace('s','');
.去除回车:s =s.replace('n','');
这样也可以把空格和回车去掉,其他也可以照这样做。
注:n 回车(u000a)
t 水平制表符(u0009)
s 空格(u0008)
r换行(u000d)*/
}