Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 40: Write a Java program to replace occurrence of every with the other character entered by the user in the given string.

Replace.java

import java.util.Scanner;

public class Replace
{
	//Method to replace every occurrence of c1 in string with c2.
	public static String replaceCharacter(String input, char c1, char c2)
	{
        for(int i=0; i < input.length();i++)
        {
            if(input.charAt(i)==c1)
            {
                input=input.substring(0,i)+c2+input.substring(i+1);
            }
        }
        return input;
	}

	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the string.");
		String input = s.next();

		System.out.println("Enter the character to be replaced in the string.");
		char c1 = s.next().charAt(0);

		System.out.println("Enter the replacing character.");
		char c2 = s.next().charAt(0);

		System.out.println(Replace.replaceCharacter(input, c1, c2));
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected].com or just comment below.