我正在尝试制作一个比较两个字符串并用星号替换并发字符的方法,以供初学者练习。我认为在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();
}}
如果我插入字符串1,并插入字符串2,我得到这些:five fingersfivefiv* fing*rs
虽然我期待一些喜欢**** **ng*rs
有人能告诉我我做错了什么吗?谢谢!!
Helenr
万千封印
相关分类