简体   繁体   中英

Common length of strings in java

In this java program everything works fine but at the last i have to get the number of words matched in length of character but i cant how to get it?

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);

Use a counter

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);
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);

I think this is what you are looking for.

You need to count the number of matches in your loop, then after looping display the number of letters that are in both arrays.

如果目标是获取两个字符串之间的公共字符数,则一种方法是将两个字符串都转换为字符集,并在两个字符集之间进行交集并获取其大小。

If you want the number of times a character in s1 also appears in 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);

If instead you want the number of distinct characters shared by s1 and 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM