Подтвердить что ты не робот

Замените String другим в java

Какая функция может заменить строку другой строкой?

Пример №1: что заменит "HelloBrother" на "Brother"?

Пример # 2: что заменит "JAVAISBEST" на "BEST"?

4b9b3361

Ответ 1

Метод replace - это то, что вы ищете.

Например:

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

Ответ 3

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

Ответ 4

Замена одной строки на другую может быть выполнена в следующих методах

Метод 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)

ССЫЛКА

Ответ 5

Существует возможность не использовать дополнительные переменные

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