×

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

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

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.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

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.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.