स्ट्रिंग को दूसरे के साथ जावा में बदलें


97

क्या कार्य एक स्ट्रिंग को दूसरे स्ट्रिंग से बदल सकता है?

उदाहरण # 1: किसके "HelloBrother"साथ बदलेगा "Brother"?

उदाहरण # 2: किसके "JAVAISBEST"साथ बदलेगा "BEST"?


2
तो आप केवल अंतिम शब्द चाहते हैं?
एसएनआर

जवाबों:



46

इसे आज़माएं: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang/CharSequence%29

String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");

System.out.println(r);

यह प्रिंट होगा "भाई आप कैसे हैं!"


6
Javadocs की एक प्राचीन प्रति का लिंक देने के लिए लगभग -1।
स्टीफन सी

10

अतिरिक्त चर का उपयोग नहीं करने की संभावना है

String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);

1
यह शायद ही कोई नया उत्तर हो, लेकिन @ डेडप्रोग्रामर के उत्तर में सुधार।
कार्ल रिक्टर

यह मौजूदा उत्तर है, कृपया अलग-अलग दृष्टिकोण @oleg sh
Lova Chittumuri

7

एक स्ट्रिंग को दूसरे के साथ बदलना नीचे के तरीकों से किया जा सकता है

विधि 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)

संदर्भ



0

एक अन्य सुझाव, मान लें कि आपके स्ट्रिंग में दो समान शब्द हैं

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.
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.