public class findMatching {
public static void main(String[] args) {
String matchOne = "caTch";
String matchTwo = "cat";
findMatching(matchOne, matchTwo);
}
public static void findMatching(String matchOne, String matchTwo) {
int lengthOne = matchOne.length();
int lengthTwo = matchTwo.length();
char charOne;
char charTwo;
while(!matchOne.equals(matchTwo)) {
for(int i = 0; i < lengthOne && i < lengthTwo; i++) {
charOne = matchOne.charAt(i);
charTwo = matchTwo.charAt(i);
if(charOne == charTwo && lengthOne >= lengthTwo) {
System.out.print(charOne);
} else if (charOne == charTwo && lengthTwo >= lengthOne){
System.out.print(charTwo);
} else {
System.out.print(".");
}
}
}
}
}
我创建了一个名为 findMatching 的静态方法,它接受两个字符串参数,然后比较它们是否匹配字符。如果检测到匹配的字符,则打印所述字符,而不匹配的字符则用“.”表示。相反。
EX: for
caTch
andcat
, the expected output should beca...
where the non-matching characters are represented with "." in the longer string.
但是现在,我的程序的输出仅打印出ca.
,因为它只打印较短字符串的不匹配字符。我相信问题的根源可能在于 lengthOne 和 lengthTwo 的 if 语句的逻辑。
最佳答案
一旦达到较短字符串的长度,您的 for 循环就会终止 i < lengthOne && i < lengthTwo
。因此,您需要保持循环,直到到达较长字符串的末尾,但当较短字符串没有字符时停止比较。
像这样的东西就可以完成这项工作
public static void findMatching(String matchOne, String matchTwo) {
int lengthOne = matchOne.length();
int lengthTwo = matchTwo.length();
char charOne;
char charTwo;
for(int i = 0; i < lengthOne || i < lengthTwo; i++) {
if(i < lengthOne && i < lengthTwo) {
charOne = matchOne.charAt(i);
charTwo = matchTwo.charAt(i);
if (charOne == charTwo) {
System.out.print(charTwo);
} else {
System.out.print(".");
}
} else {
System.out.print(".");
}
}
}
我不确定 while 循环的意义是什么,因为它会让程序永远运行,但是也许您希望将其作为 if ?
关于java - 查找两个字符串之间的匹配字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58599337/