java 去空格
程序员文章站
2022-03-15 20:54:14
...
1.trim() 方法用于删除字符串的头尾空白符。
public class Test {
public static void main(String args[]) {
String Str = new String(" hello word ");
System.out.println( Str );
System.out.print("删除空格 :" );
System.out.println(Str.trim());
}
}
2.replace(" ", "") 去掉所有空格
public class Test {
public static void main(String args[]) {
String str = " hello word ";
String str2 = str.replaceAll(" ", "");
System.out.println(str2);
}
}
3.deleteWhitespace 去掉所有空格
public class Test {
public static void main(String args[]) {
String str = " hello word ";
String str1 = StringUtils.deleteWhitespace(str);
System.out.println(str1);
}
}
maven下载该jar org.apache.commons.lang.StringUtils
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
源码:
public static String deleteWhitespace(String str)
{
if (isEmpty(str))
return str;
int sz = str.length();
char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; ++i)
if (!(Character.isWhitespace(str.charAt(i))))
chs[(count++)] = str.charAt(i);
if (count == sz)
return str;
return new String(chs, 0, count);
}
上一篇: vivoT1手机值不值得入手?vivoT1详细评测
下一篇: 我这样凶