Advertisement
Shailrshah

Replace a Character from a String

Dec 18th, 2013
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. import java.util.Scanner;
  2. class testHello{
  3.         public static void main(String args[]){
  4.                 Scanner sc = new Scanner(System.in);
  5.                 System.out.print("Enter a string: ");
  6.                 String string = sc.nextLine();
  7.                 System.out.print("Enter a character to be replaced: ");
  8.                 char replace = sc.next().charAt(0);
  9.                 System.out.print("Enter the replacement character: ");
  10.                 char replacement = sc.next().charAt(0);
  11.                 String output = "";
  12.                 for(int i = 0; i < string.length(); i++)
  13.                         if(string.charAt(i) == replace) output += replacement;
  14.                         else output += string.charAt(i);
  15.                 System.out.print("The new string is: "+output);
  16.         }
  17. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement