在这个java程序中一切正常,但最后我必须得到字符长度匹配的单词数量,但我不知道如何得到它?
Scanner input = new Scanner(System.in);
String s1 = "Enter the name 1:";
System.out.println(s1);
s1 = input.next();
String s2 = "Enter the name 2:";
System.out.println(s2);
s2 = input.next();
if (s1.equals(s2)) {
System.out.println("They match");
} else {
System.out.println("They dont match");
}
char[] c = s1.toCharArray();
char[] d = s2.toCharArray();
for (char i = 0; i < c.length; i++) {
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
System.out.println("The number of letters matched are :" + c[i]);
}
}
}
System.out.println("The number of letters matched are :" + c.length);
答案 0 :(得分:1)
使用计数器
int counter = 0 ;
for (char i = 0; i < c.length; i++) {
boolean found = false;
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
found = true;
System.out.println("The number of letters matched are :" + c[i]);
break;
}
}
if(found){
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);
答案 1 :(得分:0)
char[] c = s1.toCharArray();
char[] d = s2.toCharArray();
int count = 0;
for (char i = 0; i < c.length; i++) {
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
count++;
}
}
}
System.out.println("The number of letters matched are :" + count);
我认为这就是你要找的东西。
您需要计算循环中的匹配数,然后在循环后显示两个数组中的字母数。
答案 2 :(得分:0)
如果目标是获取两个字符串之间的公共字符数,那么一种方法是将两个字符串转换为字符集,并设置两个字符集之间的交集并获得其大小。
答案 3 :(得分:0)
如果你想要s1中的一个角色出现在s2中的次数:
int counter = 0;
for (int i=0; i<s1.length(); i++) {
if (s2.indexOf(s1.charAt(i)) >= 0) {
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);
如果您想要由s1和s2共享的不同字符数:
Set<Character> set = new HashSet<>();
int counter = 0;
for (int i=0; i<s1.length(); i++) {
set.add(s1.charAt(i));
}
for (int j=0; j<s2.length(); j++) {
if (set.contains(s2.charAt(j))) {
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);