Java替换字符串中的字符,变量中的给定值除外
我需要一些帮助。 因此,任务如下: 创建一个要求输入主要短语的程序。请求保留在短语中的键字符串值。显示原始主短语的版本,其中所有字符都已替换为加号(“+”),但保留不变的键字符串值的外观除外。 样本输出:
------------------------------------------------
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
这是我的密码:
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");
}
}
}
}
有人能帮我吗 谢谢
# 1 楼答案
为什么不将replaceAll与not短语一起使用呢,请使用以下表达式“?!({您的短语})”
# 2 楼答案
x
是char
而key
是String
:条件不应是x.contains(key)
# 3 楼答案
使用此选项而不是循环: