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
使用这个而不是你的循环:
System.out.println(phrase.replaceAll("[^" + key + "]", plus));
为什么不将 replaceAll 与 not phrace 一起使用,请使用此表达式“?!.({您的短语})”
x
是一个char
, key
是一个String
:条件不应该是x.contains(key)
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.