【发布时间】:2019-04-10 16:32:03
【问题描述】:
我正在尝试制作一种方法来比较两个字符串并用星号替换并发字符以供初学者练习。 我想在 String 类或其他类中已经存在一些方法可以做到这一点,但是练习不允许我使用它们。 我试图用for循环来做。这是我的代码:
public void substrings(){
System.out.println ("Insert string 1 and press Intro");
String string1 = sc.nextLine();
System.out.println ("Insert string 2 and press Intro");
String string2 = sc.nextLine();
String major;
String minor;
if (string1.length() >= string2.length()){
major = string1;
minor = string2;
}
else{
major = string2;
minor = string1;
}
char[]replace = new char[major.length()];
for (int i = 0; i < major.length(); i++){
for (int j = 0; j < minor.length(); j++){
if (major.charAt(i) != minor.charAt(j)){
replace[i] = major.charAt(i);
}
else {
replace[i] = '*';
}
}
System.out.print (replace[i]);
}
System.out.print ("\n");
}
public static void main (String[]args){
Substrings Test = new Substrings();
Test.substrings();
}}
如果我将 five fingers 作为字符串 1 插入,并将 five 作为字符串 2 插入,我会得到这些:
fiv* fing*rs
虽然我期待像**** **ng*rs这样的人
谁能告诉我我做错了什么?谢谢!!
【问题讨论】:
-
在 Java 8 中更容易:
string1.chars().mapToObj(e -> String.valueOf((char) (string2.chars().anyMatch(e2 -> e == e2) ? '*' : e) )).forEach(System.out::print);