John Michael Rivera John Michael Rivera - 2 months ago 6
Java Question

Java replace characters in a string except for the given value in a variable

Need some help.
So here is the task:
Create a program that will ask for a main phrase. Ask for a key string value that will be preserved in the phrase. Display a version of the original main phrase where all chars have been replaced by pluses ("+"), except for appearances of the key string value which are preserved unchanged.

Sample outputs:



Enter main phrase: 12xy34
Enter key string:xy

New Version: ++xy++



Enter main phrase: 12xy34
Enter key string:1

New Version: 1+++++



Enter main phrase: 12xy34xyabcxy
Enter key string:xy
New Version: ++xy++xy+++xy

Here is my code:

import java.util.*;
public class Corpuz_Kervin
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
String phrase,key= "";
String plus = "+";


System.out.print("Enter main phrase : ");
phrase = input.nextLine();
System.out.print("Enter key string : ");
key = input.nextLine();



for (int i = 0; i < phrase.length(); i++)
{
char x = phrase.charAt(i);
if (x.contains(key))
{
System.out.print(phrase.replace(x),"+");
}
else
{
System.out.print("Error");
}
}
}
}


Can anyone help me
Thanks

Answer

Use this instead of your loop:

System.out.println(phrase.replaceAll("[^" + key + "]", plus));
Comments