заменить строку на другую в java
Какая функция может заменить строку на другую строку?
Пример # 1: Что будет заменено "HelloBrother" на "Brother"?
"HelloBrother"
"Brother"
Пример №2: Что будет заменено "JAVAISBEST" на "BEST"?
"JAVAISBEST"
"BEST"
Переведено автоматически
Ответ 1
Метод replace - это то, что вы ищете.
replace
Например:
String replacedString = someString.replace("HelloBrother", "Brother");
Ответ 2
Попробуйте это:https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.Последовательность символов,%20java.lang.Последовательность символов,%29
String a = "HelloBrother How are you!";String r = a.replace("HelloBrother","Brother");System.out.println(r);
Это выведет "Брат, как дела!"
Ответ 3
Есть возможность не использовать дополнительные переменные
String s = "HelloSuresh";s = s.replace("Hello","");System.out.println(s);
Ответ 4
Заменить одну строку на другую можно следующими способами
Метод 1: Использование строки replaceAll
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
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, как определено в ссылке ниже:
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)
ССЫЛКА