Regular Expression "\\s" จับคู่ช่องว่างในสตริง เมธอด replaceAll() รับสตริงและ regular expression แล้วแทนที่ตัวอักษรที่จับคู่ได้ด้วยสตริงที่กำหนด เพื่อลบช่องว่างทั้งหมดจากสตริงอินพุต ให้เรียกเมธอด replaceAll() พร้อม regular expression ด้านบนและสตริงว่างเป็นอาร์กิวเมนต์
ตัวอย่างที่ 1: ใช้ replaceAll()
public class RemovingWhiteSpaces {
public static void main(String args[]) {
String input = "Hi welcome to tutorialspoint";
String regex = "\\s";
String result = input.replaceAll(regex, "");
System.out.println("Result: " + result);
}
}
Output
Result: Hiwelcometotutorialspoint
ตัวอย่างที่ 2: ใช้ appendReplacement()
เช่นเดียวกัน เมธอด appendReplacement() รับ StringBuffer และสตริงแทนที่ แล้วนำตัวอักษรที่จับคู่ได้ไปแทนที่ด้วยสตริงแทนที่และผนวกเข้า StringBuffer
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemovingWhiteSpaces {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "\\s";
String constants = "";
System.out.println("Input string: \n" + input);
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// จับคู่ pattern ที่คอมไพล์แล้วในสตริง
Matcher matcher = pattern.matcher(input);
// สร้าง StringBuffer ว่าง
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
constants = constants + matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n" + sb.toString() + constants);
}
}
Output
Enter input string: this is a sample text with white spaces Input string: this is a sample text with white spaces Result: thisisasampletextwithwhitespaces
ตัวอย่างที่ 3: ใช้ split() และ loop
public class Just {
public static void main(String args[]) {
String input = "This is a sample text with spaces";
String str[] = input.split(" ");
String result = "";
for (int i = 0; i < str.length; i++) {
result = result + str[i];
}
System.out.println("Result: " + result);
}
}
Output
Result: Thisisasampletextwithspaces