×

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method.

String Replace

It returns a string replacing all old characters with new characters or sequences.

Syntax:

String replace(previous char character, new character)

Using this method, you can change the similar characters of the String with a new character. Both old and character are passed as parameters to the replace method.

Return Value: It returns a string with old characters replaced by new characters, passed as parameters to the replace method.

Program for Replace method for strings in Java

//Replace method in Java
public class Main {
    public static void main(String args[])
    {
        // Declaration of string
        String s = new String("Hello everyone");
       // Before replacing characters 
        System.out.print("String before replacing : ");
        System.out.println(s);
        System.out.print("After replacing all e with x : ");
        System.out.println(s.replace('e', 'x'));
  
        // Using replace to replace characters
        System.out.print("After replacing all o with r: ");
        System.out.println(s.replace('o', 'r'));
    }
}

Output

Program to find and replace characters on string in java

Explanation

In the above program, string variable s is assigned to "Hello everyone". Using the predefined method replace(), we have replaced the character 'e' with 'x' and 'o' with 'r'.

2. Replace(CharSequence target, CharSequence replacement) method

  • Program for replace method to replace character sequence
public class Main{  
public static void main(String args[]){  
//string declaration
String s1="It is rainy";  
System.out.print("Original string is: ");
System.out.println(s1);
String replaceString=s1.replace("is","was");//replacing all occurrences of "is" to "was"  
System.out.print("After replacement: ");
System.out.println(replaceString);  
}}  

Output

Program to find and replace characters on string in java

Explanation

In the above program, string variable s1 is assigned to “It is rainy". Using the predefined method replace(), we have replaced the word ‘is’ with ‘was'.

  • Program for replacing method to replace character sequence
public class Main  
{  
// main method  
public static void main(String argvs[])  
{  
String s = "Java programming language is very important ";  
int size = s.length();  
System.out.println(s);  
String t = null;  
// replacing null with Python. Hence, the NullPointerException is raised.  
s = s.replace(t, "Python");  
System.out.println(s); 
}  
}

Output

Program to find and replace characters on string in java

Explanation

In the above program, string variable s is assigned to "Java programming language is very important ". Using the predefined method, replace(), we have replaced the variable t with the name "Python".

Replace First()

This function replaces the first word if the passed String is matched.

Syntax:

 public String replace First(String original, String replace)

Program for replacing the first method

public class Main {
    public static void main(String args[])
    {
        //  String Initialisation
        String Str = new String("Hi Everyone");
        // original string
        System.out.print("Original String : ");
        System.out.println(Str);
        System.out.print("Replacing first occurrence of regex with replace_str : ");
        System.out.println(
            Str.replaceFirst("Hi", "With"));
    }
}

Output

Program to find and replace characters on string in java

Explanation

In the above program, string variable s is assigned to "Hi Everyone ". Using the predefined method replaceFirst(), we have replaced the word “Hi” with the word “with".

Replace all

The method uses the provided replace str to replace each substring of the String that matches the provided regular expression.

Syntax:

public String replaceAll(String regex, String replace_str)

1. Program for string replace

public class Main{  
public static void main(String args[]){  
System.out.print("Original string: ");


String s1="Hello everyone";  
System.out.println(s1);


System.out.println("Reverse string: ");
String replaceString=s1.replaceAll("e","a"); //replaces all occurrences of "a" to "e"  
System.out.println(replaceString);  
}
}  

Output

Program to find and replace characters on string in java

Explanation

In the above program, string variable s is assigned to "Hi Everyone ". Using the predefined method replaceAll(), we have replaced the character 'e' with the character ' a'. 

2. Program for String replace

public class Main{
    public static void main(String s[])
    {
        // Initialising String
        String Str = new String("Hello everyone");
        // original string
        System.out.print("Original String : ");
        System.out.println(Str);
        System.out.print("Replacing regex with replace_str : ");
        System.out.println(Str.replaceAll("Hello", "Hi"));
    }
}

Output

Program to find and replace characters on string in java

Explanation

In the above program, string variable s is assigned to "Hello Everyone ". Using the predefined method replaceAll(), we have replaced the word “Hello” with “Hi”.

3. Program for String replace

public class Main
{
public static void main(String args[])
{
String s = "Hi everyone";
System.out.print("Original string is :");
System.out.println(s);
String r = "";
System.out.println("replaced string is: ");
s = s.replaceAll(r," ");
System.out.println(s);
}  
}  

Output

Program to find and replace characters on string in java

Explanation

In the above program, string variable s is assigned to "Hi Everyone ". Using the predefined method replaceAll(), we have replaced the word "Hi” with “ ”.


Related Topics

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.