-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReplaceAllCharacters.java
49 lines (44 loc) · 1.15 KB
/
ReplaceAllCharacters.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.javamultiplex.string;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ReplaceAllCharacters {
public static void main(String[] args) {
Scanner input=null;
try
{
input=new Scanner(System.in);
System.out.println("Enter String : ");
String string=input.nextLine();
int length=string.length();
System.out.println("Enter character that you want to replace : ");
char character1=input.next(".").charAt(0);
System.out.println("Enter new character that you want to replace with old character : ");
char character2=input.next(".").charAt(0);
StringBuilder newstring=new StringBuilder();
for(int i=0;i<length;i++)
{
if(string.charAt(i)==character1)
{
newstring.append(character2);
}
else
{
newstring.append(string.charAt(i));
}
}
System.out.println("String after replacement : ");
System.out.println(newstring.toString());
}
catch(InputMismatchException exception)
{
System.out.println("Please enter valid character.");
}
finally
{
if(input!=null)
{
input.close();
}
}
}
}