रेगुलर एक्सप्रेशन "\\s" स्ट्रिंग में स्पेस से मिलान करता है। replaceAll() मेथड एक स्ट्रिंग और एक रेगुलर एक्सप्रेशन स्वीकार करता है और मिलान किए गए वर्णों को दी गई स्ट्रिंग से बदल देता है। इनपुट स्ट्रिंग से सभी व्हाइट स्पेस हटाने के लिए, उस पर replaceAll() मेथड को उपरोक्त रेगुलर एक्सप्रेशन और एक खाली स्ट्रिंग के साथ इनपुट के रूप में लागू करें।
उदाहरण 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);
}
}
आउटपुट
परिणाम: Hiwelcometotutorialspoint
उदाहरण 2 (appendReplacement() का उपयोग करके)
इसी तरह, appendReplacement() मेथड एक स्ट्रिंग बफर और एक रिप्लेसमेंट स्ट्रिंग स्वीकार करता है, और मिलान किए गए वर्णों को दी गई रिप्लेसमेंट स्ट्रिंग से जोड़ता है और स्ट्रिंग बफर में जोड़ता है।
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("इनपुट स्ट्रिंग दर्ज करें: ");
String input = sc.nextLine();
String regex = "\\s";
String constants = "";
System.out.println("इनपुट स्ट्रिंग: \n" + input);
// पैटर्न ऑब्जेक्ट बनाना
Pattern pattern = Pattern.compile(regex);
// स्ट्रिंग में कंपाइल्ड पैटर्न का मिलान
Matcher matcher = pattern.matcher(input);
// खाली स्ट्रिंग बफर बनाना
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
constants = constants + matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("परिणाम: \n" + sb.toString() + constants);
}
}
आउटपुट
इनपुट स्ट्रिंग दर्ज करें: this is a sample text with white spaces इनपुट स्ट्रिंग: this is a sample text with white spaces परिणाम: thisisasampletextwithwhitespaces
उदाहरण 3 (split() का उपयोग करके)
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);
}
}
आउटपुट
परिणाम: Thisisasampletextwithspaces