如何在 Java 中刪除字串中的空格
Mohammad Irfan
2023年10月12日
Java
Java String
- 在 Java 中如何刪除字串中的空白處
-
在 Java 中使用
replaceAll()刪除空白字元 -
在 Java 中使用
Apache庫刪除whitespace - 在 Java 中使用 Pattern 和 Matcher 刪除空白字元
- 在 Java 中刪除字串中的空格
-
在 Java 中使用
Apache刪除空格
本教程介紹瞭如何在 Java 中從字串中刪除空格,並列舉了一些示例程式碼來了解空格刪除過程。
在 Java 中如何刪除字串中的空白處
空格是指在字串中表示一個空格的字元,它可以是" "、\n、\t 等。要從字串中刪除這些字元,有幾種方法,例如 replace() 方法,replaceAll(),regex 等。讓我們看看下面的例子。
在 Java 中使用 replaceAll() 刪除空白字元
在這裡,我們使用 String 類的 replaceAll() 方法來刪除空格。這個方法使用一個 regex 作為引數,並在去除所有空白後返回一個字串。
public class SimpleTesting {
public static void main(String[] args) {
String str = "Programming is easy to learn";
String result = str.replaceAll("\\s+", "");
System.out.println(result);
}
}
輸出:
Programminiseasytolearn
在 Java 中使用 Apache 庫刪除 whitespace
如果你使用 Apache 庫,那麼可以使用 StringUtils 類的 deleteWhitespace() 方法在 Java 中刪除字串中的空白。請看下面的例子和輸出。
import org.apache.commons.lang3.StringUtils;
public class SimpleTesting {
public static void main(String[] args) {
String str = "Programming is easy to learn";
String result = StringUtils.deleteWhitespace(str);
System.out.println(result);
}
}
輸出:
Programminiseasytolearn
在 Java 中使用 Pattern 和 Matcher 刪除空白字元
我們可以使用 Pattern 和 Matcher 類與 replaceAll() 方法來刪除 Java 字串中的所有空格。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SimpleTesting {
public static void main(String[] args) {
String str = "Programming is easy to learn";
Pattern p = Pattern.compile("[\\s]");
Matcher m = p.matcher(str);
String result = m.replaceAll("");
System.out.println(result);
}
}
輸出:
Programminiseasytolearn
在 Java 中刪除字串中的空格
如果你只想從一個字串中刪除空格,那麼使用 String 類的 replace() 方法。在 Java 中,它將替換掉字串中所有的空格(不是所有的空白符號,比如\t,\n 不會被刪除。)。
public class SimpleTesting {
public static void main(String[] args) {
String str = "Programming is easy to learn";
String result = str.replace(" ", "");
System.out.println(result);
}
}
輸出:
Programminiseasytolearn
在 Java 中使用 Apache 刪除空格
在這裡,我們使用 Apache 的 StringUtils 類的 replace() 方法來替換 Java 中字串的所有空格。
import org.apache.commons.lang3.StringUtils;
public class SimpleTesting {
public static void main(String[] args) {
String str = "Programming is easy to learn";
String result = StringUtils.replace(str, " ", "");
System.out.println(result);
}
}
輸出:
Programminiseasytolearn
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe