String'i java'da başka biriyle değiştirin


97

Bir dizeyi başka bir dizeyle hangi işlev değiştirebilir?

Örnek 1: Ne "HelloBrother"ile değiştirilecek "Brother"?

Örnek 2: Ne "JAVAISBEST"ile değiştirilecek "BEST"?


2
Yani sadece son sözü mü istiyorsun?
SNR

Yanıtlar:


147

replaceYöntem aradığınız budur.

Örneğin:

String replacedString = someString.replace("HelloBrother", "Brother");


10

Ekstra değişken kullanmama olasılığı var

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

1
Bu pek yeni bir cevap değil, ancak @ DeadProgrammer'ın cevabında bir gelişme.
Karl Richter

Bu mevcut cevap lütfen farklı bir yaklaşımla deneyin @oleg sh
Lova Chittumuri

7

Bir dizeyi diğeriyle değiştirmek aşağıdaki yöntemlerle yapılabilir.

Yöntem 1: Dize KullanmareplaceAll

 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);       

Yöntem 2 : KullanmaPattern.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);           

Yöntem 3 : Apache CommonsAşağıdaki bağlantıda tanımlandığı şekilde kullanın:

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)

REFERANS



0

Başka bir öneri, Dize de iki aynı kelimeye sahip olduğunuzu varsayalım

String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.

değiştirme işlevi, ilk parametrede verilen her dizeyi ikinci parametreye değiştirir

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

ve aynı sonuç için replaceAll yöntemini de kullanabilirsiniz

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

yalnızca daha önce konumlandırılan ilk dizeyi değiştirmek istiyorsanız,

System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.