การลบช่องว่าง (Whitespace) ทั้งหมดจากสตริงใน Java
ใช้เมธอด replaceAll(String regex, String replacement) กับ Regular Expression \\s ซึ่งจับคู่ whitespace ทุกประเภท (space, tab, newline, carriage return, form feed)
ไวยากรณ์
String result = inputString.replaceAll("\\s", "");
ตัวอย่างโค้ดสมบูรณ์
public class Demo {
public static void main(String[] args) {
String inputString = "Java programming is fun to learn.";
System.out.println("สตริงต้นฉบับ: " + inputString);
// ลบ whitespace ทั้งหมด
String result = inputString.replaceAll("\\s", "");
System.out.println("หลังลบช่องว่าง: " + result);
}
}
ผลลัพธ์
สตริงต้นฉบับ: Java programming is fun to learn.
หลังลบช่องว่าง: Javaprogrammingisfuntolearn.
ตัวอย่างที่ 2: แบบ OOP (Encapsulation)
public class Demo {
public static String removeAllWhitespace(String input) {
if (input == null) return null;
return input.replaceAll("\\s", "");
}
public static void main(String[] args) {
String input = "Java programming is fun to learn.";
System.out.println("ต้นฉบับ: " + input);
System.out.println("ผลลัพธ์: " + removeAllWhitespace(input));
// ทดสอบกรณีต่างๆ
System.out.println(removeAllWhitespace("Hello\tWorld\nNew\rLine")); // HelloWorldNewLine
System.out.println(removeAllWhitespace(null)); // null
}
}
Regular Expression สำหรับ Whitespace
| Regex | ความหมาย | ตัวอย่างที่จับได้ |
|---|---|---|
\\s |
Whitespace ทุกประเภท | space, tab, \n, \r, \f |
\\s+ |
Whitespace ติดกัน 1+ ตัว | " ", "\t\n" |
(space) |
เฉพาะ space bar | " " |
\\t |
เฉพาะ tab | "\t" |
วิธีอื่นๆ
1. replace() - แทนที่เฉพาะ space (ไม่ใช่ regex)
String result = input.replace(" ", ""); // ลบเฉพาะ space, ไม่ลบ tab/newline
2. StringBuilder - ประสิทธิภาพดีกว่าสำหรับสตริงยาว
public static String removeWhitespaceSB(String input) {
if (input == null) return null;
StringBuilder sb = new StringBuilder(input.length());
for (char c : input.toCharArray()) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
3. Stream API (Java 8+)
String result = input.chars()
.filter(c -> !Character.isWhitespace(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
4. Apache Commons Lang
StringUtils.deleteWhitespace(input); // null-safe
การทดสอบประสิทธิภาพ (Benchmark)
// สำหรับสตริงสั้น: replaceAll("\\s", "") ใช้งานง่ายพอ
// สำหรับสตริงยาว/ทำบ่อย: StringBuilder หรือ deleteWhitespace() เร็วกว่า
// replaceAll คอมไพล์ regex ทุกครั้ง (ยกเว้นจะ cache Pattern ไว้)
ข้อควรระวัง
replaceAllใช้ Regex → ต้อง escape backslash:\\\\sในโค้ด Javanullinput จะโยน NPE → ต้องตรวจสอบ null ก่อนtrim()ลบเฉพาะหัว/ท้าย ไม่ใช่กลางสตริง- Unicode whitespace อื่นๆ (non-breaking space ฯลฯ)
\\sจับได้ครบใน Java