Java

Java String replace Method

With the string class in Java, all occurrences of the same character in the string can be replaced with a different character. All occurrences of the same substring in a string can be replaced with a different substring. Just the first substring found in a string can be replaced by a different substring. This article explains how all that is done. The string class has methods for this. The syntaxes are:

public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
public String replaceAll(String regex, String replacement)
public String replaceFirst(String regex, String replacement)

Replacing Characters

All the same characters in a string can be replaced by a new character. The syntax of the string method, to do this, is:

public String replace(char oldChar, char newChar)

A new string is returned. The following program prints the old and new strings:

    public class TheClass {
        public static void main(String[] args) {
            String OldStr = "We are growing higher and higher";
            String newStr = OldStr.replace('i', 'u');
            System.out.println(OldStr);
            System.out.println(newStr);
        }
    }

The output is:

We are growing higher and higher
We are growung hugher and higher

The old string is unchanged. The returned string has the change. In order to use a string method, no string class has to be imported. The main method of this short program has all the code. Note how the to replace method has been used.

Replacing Substrings

All of the same substrings in a string can be replaced. The syntax for this is:

public String replace(CharSequence target, CharSequence replacement)

A new string is returned. The following program prints the old and new strings:

    public class TheClass {
        public static void main(String[] args) {
            String OldStr = "He likes me. He likes him.";
            String target = "He", replacement = "She";
            String newStr = OldStr.replace(target, replacement);
            System.out.println(OldStr);
            System.out.println(newStr);
        }
    }

The output is:

He likes me. He likes him.
She likes me. She likes him.

The old string is unchanged. The returned string has the change. In order to use a string method, no string class has to be imported. The main method of this short program has all the code. Note how the to replace method has been used.

The replaceAll Method

The replaceAll() method behaves in the same way as the above method. However, here, the argument for the substring to replace is a regex – see later.

All of the same substrings in a string can be replaced. The syntax for this is:

public String replaceAll(String regex, String replacement)

A new string is returned. The following program prints the old and new strings:

    public class TheClass {
        public static void main(String[] args) {
            String OldStr = "He likes me. He likes him.";
            String regex = "He", replacement = "She";
            String newStr = OldStr.replaceAll(regex, replacement);
            System.out.println(OldStr);
            System.out.println(newStr);
        }
    }

The output is:

He likes me. He likes him.
She likes me. She likes him.

The old string is unchanged. The returned string has the change. In order to use a string method, no string class has to be imported. The main method of this short program has all the code. Note how the replaceAll method has been used.

Replacing the First Substring

If more than one substring is in the string, only the first one can be replaced. The syntax is:

public String replaceFirst(String regex, String replacement)

A new string is returned. The following program prints the old and new strings:

    public class TheClass {
        public static void main(String[] args) {
            String OldStr = "Yes, he likes me. No, he likes him.";
            String regex = "he", replacement = "She";
            String newStr = OldStr.replaceFirst(regex, replacement);
            System.out.println(OldStr);
            System.out.println(newStr);
        }
    }

The output is:

Yes, he likes me. No, he likes him.
Yes, She likes me. No, he likes him.

The old string is unchanged. The returned string has the change. Only the first substring has been replaced. In order to use a string method, no string class has to be imported. The main method of this short program has all the code. Note how the replaceFirst method has been used.

Using the for-Loop for Characters

The for-loop can be used to replace all of the same old characters with a new character. The idea is to read all the characters in the string; any character that is a target is replaced. The following program illustrates this, for a target character of ‘i’, and a replacement character of ‘u’:

    public class TheClass {
        public static void main(String[] args) {
            String str = "We are growing higher and higher";
            StringBuffer oldStr =  new StringBuffer(str);
            int len = oldStr.length();
     
            for (int i=0; i<len; i++) {
                if (oldStr.charAt(i) == 'i')
                    oldStr.setCharAt(i, 'u');
            };
            System.out.println(oldStr);
        }
    }

The output is:

We are growung hugher and higher

Only the old string has been displayed here. It is the old string that has been modified. A string from the  String class cannot be modified. So the StringBuffer class, which does not also have to be imported, was used. A string of a StringBuffer class can be modified.

In this program, the old string content was used in the construction of the StringBuffer object. This object has the length() method, which was used to obtain the length of the old string. It also has the charAt() method used to return the char value. Still, it has the setCharAt() method, which was used to set the new char value. The println() method would print a StringBuffer object.

Conclusion

With the string class in Java, all occurrences of the same character in the string can be replaced with a different character. All occurrences of the same substring in a string can be replaced with a different substring. The first substring found in a string can be replaced by a different substring. This article has explained how all that is done. The string class has methods for this. The syntaxes are:

public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
public String replaceAll(String regex, String replacement)
public String replaceFirst(String regex, String replacement)

The String class does not have to be imported for this program.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.