उदाहरण
public class Demo {
static String replaceWord(String sentence, String pattern) {
String[] wordList = sentence.split("\\s+");
String myResult = "";
String asteriskVal = "";
for (int i = 0; i < pattern.length(); i++)
asteriskVal += '*';
int myIndex = 0;
for (String word : wordList) {
if (word.compareTo(pattern) == 0)
wordList[myIndex] = asteriskVal;
myIndex++;
}
for (String word : wordList)
myResult += word + ' ';
return myResult.trim();
}
public static void main(String[] args) {
String sentence = "This is a sample only, the sky is blue, water is transparent";
String pattern = "sample";
System.out.println(replaceWord(sentence, pattern));
}
}
आउटपुट
This is a ****** only, the sky is blue, water is transparent
व्याख्या: Demo क्लास में 'replaceWord' नामक एक फंक्शन होता है जो वाक्य और पैटर्न को पैरामीटर के रूप में लेता है। एक वाक्य को विभाजित करके स्ट्रिंग ऐरे में संग्रहीत किया जाता है। एक खाली स्ट्रिंग परिभाषित की जाती है, और पैटर्न की लंबाई के आधार पर उस पर पुनरावृति की जाती है।
एक एस्टेरिस्क मान को '*' के रूप में परिभाषित किया जाता है और वाक्य में प्रत्येक वर्ण के लिए, वर्ण की तुलना पैटर्न से की जाती है और एक विशिष्ट घटना को एस्टेरिस्क प्रतीक से बदल दिया जाता है। अंतिम स्ट्रिंग कंसोल पर प्रदर्शित होती है।
सुधारित संस्करण (रेगुलर एक्सप्रेशन के साथ):
public static String replaceWordRegex(String sentence, String pattern) {
// शब्द सीमाओं का उपयोग करके सटीक मिलान
return sentence.replaceAll("\\b" + Pattern.quote(pattern) + "\\b",
"*".repeat(pattern.length()));
}
// Java 11+ के लिए repeat() मेथड, अन्यथा:
String asterisks = new String(new char[pattern.length()]).replace('\0', '*');
मुख्य सुधार:
\\bशब्द सीमाओं को सुनिश्चित करता है (आंशिक मिलान नहीं)Pattern.quote()विशेष रेगेक्स वर्णों को एस्केप करता है- केस-असंवेदनशील के लिए
(?i)फ्लैग जोड़ें
केस-असंवेदनशील संस्करण:
public static String replaceWordIgnoreCase(String sentence, String pattern) {
String regex = "(?i)\\b" + Pattern.quote(pattern) + "\\b";
String replacement = "*".repeat(pattern.length());
return sentence.replaceAll(regex, replacement);
}