0

在这个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);
4

4 回答 4

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);
于 2013-10-04T03:20:46.843 回答
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);
于 2013-10-04T03:41:49.320 回答
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);

我想这就是你要找的。

您需要计算循环中的匹配数,然后在循环后显示两个数组中的字母数。

于 2013-10-04T03:22:21.263 回答
0

如果目标是获取两个字符串之间的公共字符的数量,那么一种方法是将两个字符串都转换为字符集,并在这两个集合之间设置交集并获取其大小。

于 2013-10-04T03:33:14.297 回答