जवाबों:
replaceविधि आप जो खोज रहे हैं है।
उदाहरण के लिए:
String replacedString = someString.replace("HelloBrother", "Brother");
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
यह प्रिंट होगा "भाई आप कैसे हैं!"
अतिरिक्त चर का उपयोग नहीं करने की संभावना है
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
एक स्ट्रिंग को दूसरे के साथ बदलना नीचे के तरीकों से किया जा सकता है
विधि 1: स्ट्रिंग का उपयोग करनाreplaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
विधि 2 : का उपयोग करPattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
विधि 3 : Apache Commonsनीचे दिए गए लिंक में परिभाषित के रूप में उपयोग करना :
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
String s1 = "HelloSuresh";
String m = s1.replace("Hello","");
System.out.println(m);
एक अन्य सुझाव, मान लें कि आपके स्ट्रिंग में दो समान शब्द हैं
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
रिप्लेस फंक्शन बदलेगा हर स्ट्रिंग पहले पैरामीटर में दूसरे पैरामीटर के लिए दिया गया है
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
और आप उसी परिणाम के लिए प्रतिस्थापन विधि का भी उपयोग कर सकते हैं
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
यदि आप पहले स्ट्रिंग को बदलना चाहते हैं, जो पहले तैनात है,
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.