如何从java中从字符串中删除所有空格
时间:2020-02-23 14:34:38 来源:igfitidea点击:
在本教程中,我们将看到如何从Java中从字符串中删除所有空白符号
有多种方法可以从字符串中删除空格。
- 使用替换
- 使用迭代
使用替换:
我们只需调用ReficeAll方法即可删除如下所示的白色空间。
String result1 = str.replaceAll("\s", "");
使用迭代:
我们可以使用charat迭代字符串并检查字符是否为空白。
Java程序从字符串中删除所有空白符号
package org.igi.theitroad;
public class StringRemoveSpacesAllMain {
public static void main(String[] args) {
String str = " Hello world from theitroad.com ";
System.out.println("------------------------------");
System.out.println("Using replaceAll");
System.out.println("------------------------------");
//Using replaceAll
String result1 = str.replaceAll("\s", "");
System.out.println(result1);
String result2 = "";
//Using iteration
System.out.println("n------------------------------");
System.out.println("Using Iteration");
System.out.println("------------------------------");
for (int i = 0; i < str.length(); i++) {
if (!Character.isWhitespace(str.charAt(i))) {
result2 += str.charAt(i);
}
}
System.out.println(result2);
}
}
运行上面的程序时,我们将得到以下输出:
----------------------------- Using replaceAll ----------------------------- Helloworldfromtheitroad.com ----------------------------- Using Iteration ----------------------------- Helloworldfromtheitroad.com

