Replace word in java string

String x = "axe pickaxe";
x = x.replace("axe", "sword");
System.out.print(x);

By this code, I am trying to replace the exact word axe with sword. However, if I run this, it prints sword picksword while I would like to print sword pickaxe only, as pickaxe is a different word from axe although it contains it. How can I fix this? Thanks

asked May 12, 2015 at 6:54

Oti Na Nai's user avatar

Oti Na NaiOti Na Nai

1,2874 gold badges13 silver badges20 bronze badges

4

Use a regex with word boundaries b:

String s = "axe pickaxe";
System.out.println(s.replaceAll("\baxe\b", "sword"));

The backslash from the boundary symbol must be escaped, hence the double-backslashes.

answered May 12, 2015 at 6:58

hiergiltdiestfu's user avatar

hiergiltdiestfuhiergiltdiestfu

2,3292 gold badges25 silver badges36 bronze badges

1

Include the word boundary before and after the word you want to replace.

String x = "axe pickaxe axe";
x = x.replaceAll("\baxe\b", "sword");
System.out.print(x);

edit output

sword pickaxe sword

answered May 12, 2015 at 6:58

SubOptimal's user avatar

SubOptimalSubOptimal

22.3k3 gold badges52 silver badges67 bronze badges

0

Some other answers suggest you to use \b word boundaries to match an exact word. But \bfoo\b would match the substring foo in .foo.. If you don’t want this type of behavior then you may consider using lookaround based regex.

System.out.println(string.replaceAll("(?<!\S)axe(?!\S)", "sword"));

Explanation:

  • (?<!\S) Negative lookbehind which asserts that the match won’t be preceded by a non-space character. i.e. the match must be preceded by start of the line boundary or a space.

  • (?!\S) Negative lookahead which asserts that the match won’t be followed by a non-space character, i.e. the match must be followed by end of the line boundary or space. We can’t use (?<=^|\s)axe(?=\s|$) since Java doesn’t support variable length lookbehind assertions.

DEMO

Maroun's user avatar

Maroun

93.6k30 gold badges189 silver badges240 bronze badges

answered May 12, 2015 at 7:03

Avinash Raj's user avatar

Avinash RajAvinash Raj

171k27 gold badges227 silver badges271 bronze badges

5

System.out.println("axe pickaxe".replaceAll("\baxe\b", "sword"));

You need to use replaceAll instead of replace — because it can work with regular expressions. Then use the meta character b which is for word boundary. In order to use it you need to escape the as double so the reges become \baxe\b

answered May 12, 2015 at 6:59

Veselin Davidov's user avatar

Veselin DavidovVeselin Davidov

7,0011 gold badge15 silver badges23 bronze badges

You can use b to define the word boundary, so baxeb in this case.

x = x.replaceAll("\baxe\b");

answered May 12, 2015 at 6:59

Steve Chaloner's user avatar

Steve ChalonerSteve Chaloner

8,1221 gold badge22 silver badges38 bronze badges

If you only want to replace the first occurrence, there is a method replaceFirst in String object.

String x = "axe pickaxe";
x = x.replaceFirst("axe", "sword");
System.out.print(x); //returns sword pickaxe

answered May 12, 2015 at 7:05

Alvin Magalona's user avatar

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name.replace(old_string, new_string) with old_string being the substring you’d like to replace and new_string being the substring that will take its place.


When you’re working with a string in Java, you may encounter a situation where you want to replace a specific character in that string with another character. For instance, if you are creating a username generation program, you may want to replace certain letters with other characters to give a user a more random username.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

That’s where the String replace() method comes in. The Java replace() method is used to replace all occurrences of a particular character or substring in a string with another character or substring.

This tutorial will discuss how to use the String replace() method in Java and walk through an example of the method being used in a program.

Java Strings

Strings are used to store text-based data in programming. Strings can contain letters, numbers, symbols, and whitespaces, and can consist of zero or more characters.

In Java, strings are declared as a sequence of characters enclosed within double quotes. Here’s an example of a Java string:

String bread = “Seeded”;

In this example, we have assigned the string value Seeded to a variable called bread.

Strings are a useful data type because they allow developers to interact with text-based data that can be manipulated. Strings can be reversed, replaced, and otherwise changed using the string methods offered by Java.

When you’re working with a string, you may decide that you want to change a specific character in the string to another character. We can use the replace() method to perform such a change.

Java String replace

The Java string replace() method is used to replace all instances of a particular character or set of characters in a string with a replacement string. So, the method could be used to replace every s with a d in a string, or every “pop” with “pup”.

The syntax for the Java string replace() method is as follows:

string_name.replace(old_string, new_string);

The replace() method takes in two required parameters:

  • old_char is the character or substring you want to replace with a new character or substring.
  • new_char is the character or substring with which you want to replace all instances of old_char.

Now, replace() will replace every instance of a character or substring with a new character or substring and return a new string. So, if you only want to change one specific character in a string, the replace() method should not be used.

Additionally, replace() does not change the original string. Instead, the method returns a copy of the string with the replaced values. replace() is also case sensitive.

String replace Examples

Let’s walk through a few examples of the replace() method in action.

Replace Substring

Suppose we are building an app for a restaurant that stores the names and prices of various sandwiches on the menu. The chef has informed us that he wants to update the name of the Ham sandwich to Ham Deluxe to reflect the fact that new ingredients have been added to the sandwich. We could make this change using the following code:

Aclass ReplaceSandwiches {
	public static void main(String[] args) {
		String ham_entry = "Ham: $3.00.";
		String new_ham_entry = ham_entry.replace("Ham", "Ham Deluxe");
		System.out.println(new_ham_entry);
	}
}

Our code returns the following:

Ham Deluxe: $3.00.

Let’s break down our code. Firstly we define a class called ReplaceSandwiches, which stores the code for our program. Then we declare a variable called ham_entry which stores the name of the ham sandwich and its price.

On the next line, we use the replace() method to replace the word Ham with Ham Deluxe in the ham_entry string. The result of the replace() method is assigned to the variable new_ham_entry. Finally, our program prints the contents of new_ham_entry to the console.

Now we have the updated record for the ham sandwich.

Replace Character

Additionally, the replace() method can be used to replace an individual character with another character. For instance, suppose we misspelled the word Ham in our string. Instead of appearing as Ham, we typed in Hom. We know there is only one o in our string, and we want to replace it with an a.

We could use the following code to correct our mistake:

class FixSandwich {
	public static void main(String[] args) {
		String ham_entry = "Hom Deluxe: $3.00.";
		String new_ham_entry = ham_entry.replace("o", "a");
		System.out.println(new_ham_entry);
	}
}

Our code returns:

Ham Deluxe: $3.00. 

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Our code works in the same way as our first example, but instead of replacing a substring of characters, we instead replace an individual character. In this case, we replaced o with a.

Replace Multiple Instances

The replace() method will replace every instance of a character or substring with a new character or substring. In the above examples, we only replaced one instance of a substring and a character because there was only one instance in our string. But if multiple instances of a character or substring were present, they would all be replaced.

Suppose we have a string that stores the text that will appear on the banner, notifying customers that the restaurant with which we are working has a new menu. The banner appears as follows:

“MENU | Come see the new menu! | MENU”

The restaurant owner has decided he wants to replace the word “MENU” with his restaurant’s name, Sal’s Kitchen. We could do this using the following code:

class ChangeBanner {
	public static void main(String[] args) {
		String old_banner = "MENU | Come see the new menu! | MENU";
		String new_banner = ham_entry.replace("MENU", "Sal's Kitchen");
		System.out.println(new_banner);
	}
}

Our code returns:

Sal’s Kitchen | Come see the new menu! | Sal’s Kitchen

Our code works in the same way as our previous examples. However, because our initial string includes the word MENU twice, the replace() method replaces both instances. It’s worth noting that the lowercase word menu appears in our string too, but because replace() is case sensitive, it is not replaced.

Conclusion

The replace() method is used in Java to replace every instance of a particular character or substring with another character or substring.

This tutorial discussed how to use replace() to replace individual characters, substrings, and multiple instances of a character or a substring. We also explored a few step-by-step examples of the replace() method in action.

You’re now equipped with the information you need to replace the contents of a string using replace() in a Java program like a pro!

This method searches for a specified string or a specified value, or a regex expression by virtue of which has the same suggests returns a new string with related characters. replace() method of strings contains three variants here are three variants of replace() method.

There are 3 types that are frequently used for String.replace() and is also aid in problem solving capabilities.

  • replace()
  • replaceAll()
  • replaceFirst()

#1: String.replace()

This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters. 

Syntax:

public String replace(char oldch, char newch)

Parameters: 

  • The old character
  • The new character

Return Type:

It returns a string derived from this string by replacing every occurrence of oldch with newch.

Example

Java

public class GFG {

    public static void main(String args[])

    {

        String Str = new String("Welcome to geeksforgeeks");

        System.out.print("After replacing all o with T : ");

        System.out.println(Str.replace('o', 'T'));

        System.out.print("After replacing all e with D : ");

        System.out.println(Str.replace('e', 'D'));

    }

}

Output

After replacing all o with T : WelcTme tT geeksfTrgeeks
After replacing all e with D : WDlcomD to gDDksforgDDks

#2: String replaceAll()

This method replaces each substring of the string that matches the given regular expression with the given replace_str.

Syntax:

public String replaceAll(String regex, String replace_str)

Parameters:

  • The regular expression to which this string is to be matched.
  • The string which would replace found expression
Return Value
This method returns the resulting String

Example

Java

public class rep2 {

    public static void main(String args[])

    {

        String Str = new String("Welcome to geeksforgeeks");

        System.out.print("Original String : ");

        System.out.println(Str);

        System.out.print(

            "After replacing regex with replace_str : ");

        System.out.println(

            Str.replaceAll("(.*)geeks(.*)", "ASTHA TYAGI"));

    }

}

Output

Original String : Welcome to geeksforgeeks
After replacing regex with replace_str : ASTHA TYAGI

#3: String replaceFirst()

This method replaces the first substring of this string that matches the given regular expression with the given replace_str. 

Syntax:

public String replaceFirst(String regex, String replace_str)

Parameters

  • The regular expression to which this string is to be matched.
  • The string which would replace found expression.

Return Type: A resulting string

Example:

Java

public class rep3 {

   public static void main(String args[]) {

      String Str = new String("Welcome to geeksforgeeks");

      System.out.print("Original String : " );

      System.out.println(Str);

      System.out.print("After replacing 1st occurrence of regex with replace_str  : " );

      System.out.println(Str.replaceFirst("geeks", "ASTHA"));

   }

}

Output: 

Original String : Welcome to geeksforgeeks
After replacing 1st occurrence of regex with replace_str  : Welcome to ASTHAforgeeks

This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

We have worked with Strings and discussed a lot of operations in recent posts. Many times, we encounter a situation when we want to replace a specific character or string with another. We can replace the character or string by use of java replace method.

string replace in java

string replace() method uses to replace the content of a String with other content. Through replace() function, we can replace the old character or string with the new characters or strings. Java provides the replace() method that overloaded in the string class. Let’s discuss how to use the java replace() method and replace characters in string java.

The replace() is overloaded method in String class. It has 4 types:

1. replace(char oldCharacterName, char newCharacterName);
2. replace(charSequence OldCharSequence, charSequence newCharSequence);
3. replaceFirst(String oldSubstringName, String newSubstringName);
4. replaceAll(String oldSubstringName, String newSubstringName);

5. Difference between replace() and replaceAll()

1. replace(char oldCharacterName, char newCharacterName)

This method utilizes to replace the old character with a new character. It replaces all the occurrence of old characters with new characters. Also, Its return type is String. It takes two parameters of char types. If the old character doesn’t find it in the current String, then the String remains the same as it is. This method doesn’t change anything in the String.

stringName.replace(oldCharacter, newCharacter)

stringName: The name of the String in which you want to replace the old characters with new characters.
oldCharacter: The character which you want to replace in the String.
newCharacter: The character which will be used to replace the old character in the String.

public class StringExample
{
	public static void main(String[] args) 
	{		
		String str1 = "JavaGoal website";
		System.out.println("Before replace: "+str1);
		// Replace all the occurrence of 'a' with 'w'
		String str2 = str1.replace('a', 'w');
		System.out.println("After replace: "+str2);
		
		String str3 = "Hi Java";
		System.out.println("Before replace: "+str3);
		// Replace all the occurrence of 'r' with 'N'
		String str4 = str3.replace('r', 'N');
		// But 'r' is not presented so it remain same
		System.out.println("After replace: "+str4);
	}
}

Output: Before replace: JavaGoal website
After replace: JwvwGowl website
Before replace: Hi Java
After replace: Hi Java

2. replace(charSequence OldCharSequence, charSequence newCharSequence)

This method employs to replace the old substring with a new substring. It replaces all the occurrences of an old substring with a new substring. Its return type is String. Also, It takes two parameters of CharSequence types. It means you can replace a group of characters. If the old substring doesn’t find in the current string, then the String remains the same as it is. This method doesn’t change anything in the String.

stringName.replace(oldCharSequence, newCharSequence)

stringName: The name of string in which you want to replace the old subString with a new Substring.
oldCharSequence: The Substring which you want to replace in the String.
newCharSequence: The Substring will be used to replace the old Substring in the String.

public class StringExample
{
	public static void main(String[] args) 
	{		
		String str1 = "aabbcc aa bb cc abcaa";
		System.out.println("Before replace: "+str1);
		// Replace all the substring of "aa" with "zz"
		String str2 = str1.replace("aa", "zz");
		System.out.println("After replace: "+str2);
		
		String str3 = "Hi JavaGoal.com";
		System.out.println("Before replace: "+str3);
		// Replace all the substring of "aa" with "zz"
		String str4 = str3.replace("aa", "zz");
		// But 'aa' is not presented so it remain same
		System.out.println("After replace: "+str4);
	}
}

Output: Before replace: aabbcc aa bb cc abcaa
After replace: zzbbcc zz bb cc abczz
Before replace: Hi JavaGoal.com
After replace: Hi JavaGoal.com

3. replaceFirst(String regex, String newSubstringName):

This method applies to replace the regex with a new substring. You can directly provide any string without the regex condition. It replaces first the occurrence of substring(which matched with regex) with a new substring. Its return type is String. It takes two parameters of String types.

NOTE: If regex doesn’t find any string in the current string, then the string remains the same as it is. This method doesn’t change anything in the string.

stringName.replaceFirst(regex, newSubstring)

stringName: The name of string in which you want to replace the old subString with a new Substring.
regex: The regular expression to which this string is to be matched
newSubstring: This Substring will be used to replace the Substring that matched with regex condition.

public class ReplaceFirstExample
{
   public static void main(String args[])
   {
	   String str = "Hi Java, Let's see the Java website";
	   // It will replace only first occurrence of "Java"  
	   System.out.println(str.replaceFirst("Java", "JavaGoal"));
	   
	   //It will replace whitespace with '#'
	   System.out.println(str.replaceFirst("\s", "#"));
   }
}

Output: Hi JavaGoal, Let’s see the Java website
Hi#Java, Let’s see the Java website

4. replaceAll(String regex, String newSubstringName)

This method works to replace the old substring with a new substring. It replaces all the occurrences of an old substring with a new substring. You can give any regex condition in the first parameter. All the substring that matched with condition replaced by the newSubString. Its return type is String. It takes two parameters of String types.

stringName.replaceAll(regex, newSubstringName)

stringName: The name of string in which you want to replace the old subString with a new Substring.
regex: The regular expression to which this string is to be matched.
newSubstringName: Here, the Substring will be used to replace the Substring that matched with regex condition.

public class ReplaceFirstExample
{
   public static void main(String args[])
   {
	   String name1 = "WELCOME TO JAVAGoal website";  
	   name1 = name1.replaceAll("(.*)JAVA", "KNOWLEDGE Base");
	   System.out.println("After replace = "+name1); 	
	   
	   String name2 = "WELCOME TO JAVAGoal website";  
	   name2 = name2.replaceAll("JAVA(.*)", "KNOWLEDGE Base");
	   System.out.println("After replace= "+name2); 	
	   
	   String str = "Hi Java, Let's see the Java website";
	   //It will replace all whitespace with '#'
	   System.out.println(str.replaceAll("\s", "#"));
   }
}

Output: After replace = KNOWLEDGE BaseGoal website
After replace= WELCOME TO KNOWLEDGE Base
Hi#Java,#Let’s#see#the#Java#website

Difference between replace() and replaceAll()

As you have seen the working of replace() method and replaceAll() method. Both methods replace all the occurrences of the string. But many programmers don’t the major difference between these methods.

The replace() method can take either two chars or two CharSequences as parameters and replace all occurrences of char or String. But the replaceAll() method can take only the regex String as a parameter and replaces all the substring which matches with the given regex. So you have to use the correct method at the correct place.

Suppose if you just want to replace a simple substring(You are not using regex) then you should use replace() method because the replaceAll() method calls the java.util.regex.Pattern.compile() method each time it is called even if the given argument is not a regular expression. This creates a performance issue and can introduce a bug in the code.

Понравилась статья? Поделить с друзьями:
  • Replace one word in a movie
  • Replace word in files linux
  • Replace one word games
  • Replace word in file python
  • Replace word in all files