How to replace a word in the string using Java?

by ernestina , in category: Java , 2 years ago

How to replace a word in the string using Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by orpha , 2 years ago

@ernestina  You can use the .replace() method of a string:

1
2
3
4
5
6
7
class Main {
    public static void main(String[] args) throws Exception {
        String string = "ProgrammingForm - for developers";
        // Output :computertips.info - for developers
        System.out.println(string.replace("ProgrammingForm", "computertips.info"));
    }
}


Member

by carlo , a year ago

@ernestina 

There are multiple ways to replace a word in a string using Java:

  1. Using the replace() method: This method replaces all occurrences of the specified word in the string with the replacement word. Example:
1
2
3
String originalString = "The quick brown fox jumps over the lazy dog";
String replacedString = originalString.replace("fox", "cat");
System.out.println(replacedString);


  1. Using the replaceAll() method: This method replaces all occurrences of the specified regular expression with the replacement word. Example:
1
2
3
String originalString = "The quick brown fox jumps over the lazy dog";
String replacedString = originalString.replaceAll("fox", "cat");
System.out.println(replacedString);


  1. Using the replaceFirst() method: This method replaces the first occurrence of the specified regular expression with the replacement word. Example:
1
2
3
String originalString = "The quick brown fox jumps over the lazy dog";
String replacedString = originalString.replaceFirst("fox", "cat");
System.out.println(replacedString);


  1. Using StringBuilder:
1
2
3
4
5
StringBuilder sb = new StringBuilder("The quick brown fox jumps over the lazy dog");
int startIndex = sb.indexOf("fox");
int endIndex = startIndex + "fox".length();
sb.replace(startIndex, endIndex, "cat");
System.out.println(sb.toString());


Note:

  1. The replace() and replaceAll() methods are case-sensitive. To perform a case-insensitive replacement, you can convert the string to lowercase or uppercase before calling the method.
  2. The replace() method is defined in the String class and is used to replace all occurrences of a specified string with another string.
  3. The replaceAll() method is defined in the String class and is used to replace all occurrences of a specified regular expression with another string.
  4. The replaceFirst() method is also defined in the String class and is used to replace the first occurrence of a specified regular expression with another string.