How to replace String Characters In Java Using replace() Method?

Now we are going to see the easiest way to replace characters of a string with our desired character in java using replace() method.
Below is the example of a String which we are going to replace:
“CodeSpeedy is a very good website for coding solution”

Desired String: “CodeSpeedy ps a very good webspte for codpng solutpon”

That means we have to replace the character ‘i’ with the character ‘p’

Java Program To Make Fibonacci Series With Explanation
So how to do that?
In Java, there is a method called replace (resides in java.util package), we gonna simply use that method here

import java.util.*;

public class codespeedy{
  public static void main(String[] args) {
     String str = "CodeSpeedy is a very good website for coding solution";
        String replacedstring=str.replace('i', 'p');
        System.out.println(replacedstring);
        
      }
}

The output will be like this :



CodeSpeedy ps a very good webspte for codpng solutpon

Manually Take Input From User To Replace Characters

import java.util.*;

public class codespeedy{
  public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    System.out.println("Input the String");
    String str=input.nextLine();
    System.out.println("Input the character you want to replace");
    char c = input.next().charAt(0);
    System.out.println("input the character you want to be replaced with");
    char r = input.next().charAt(0);
    
        String replacedstring=str.replace(c, r);
        System.out.println(replacedstring);
        
      }
}

This code will take the string from the user. Then it will let the user — input the desired character he/she want to be replaced with his/her desired character.

FizzBuzz Problem In Java- A java code to solve FizzBuzz problem
Output:
Input the String
Codespeedy is a very good website for coding solution
Input the character you want to replace
i
input the character you want to be replaced with
p
Codespeedy ps a very good webspte for codpng solutpon

 

Leave a Reply

Your email address will not be published. Required fields are marked *