Jaka funkcja może zastąpić ciąg innym ciągiem?
Przykład nr 1: Co zastąpi "HelloBrother"z "Brother"?
Przykład nr 2: Co zastąpi "JAVAISBEST"z "BEST"?
Jaka funkcja może zastąpić ciąg innym ciągiem?
Przykład nr 1: Co zastąpi "HelloBrother"z "Brother"?
Przykład nr 2: Co zastąpi "JAVAISBEST"z "BEST"?
Odpowiedzi:
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
To spowodowałoby wydrukowanie „Bracie jak się masz!”
Istnieje możliwość nie używania dodatkowych zmiennych
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
Zastąpienie jednego łańcucha innym można wykonać za pomocą poniższych metod
Metoda 1: użycie ciągu znakówreplaceAll
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);
Metoda 2 : UżywaniePattern.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);
Metoda 3 : Używanie Apache Commonszgodnie z definicją w linku poniżej:
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);
Kolejna sugestia, powiedzmy, że masz dwa takie same słowa w łańcuchu
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
Funkcja replace zamieni każdy łańcuch podany w pierwszym parametrze na drugi parametr
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
i możesz użyć również metody replaceAll dla tego samego wyniku
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
jeśli chcesz zmienić tylko pierwszy ciąg, który jest umieszczony wcześniej,
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.