接受2个字符串并在其中显示常用字符 [英] Accept 2 Strings and display common chars in them

查看:64
本文介绍了接受2个字符串并在其中显示常用字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码查找两个字符串中的常用字符。有时这段代码产生错误的结果,例如给出大于字符串长度的输出值。

I am using the code below to find common characters in two strings. Sometimes this code produces wrong results such as giving output value which is greater than string lengths.

for(int i = 0;i < num1.length();i++){
                for(int j =0;j < num2.length();j++){
                    if(num1.charAt(i) == num2.charAt(j)){
                        count++;
                    }
                }
            }


推荐答案

目前还不清楚你想要实现的目标。

It's not clear what you are trying to achieve.

你的代码可以产生大于字符串长度的结果,因为字符串在字符串中出现不止一次。您可以获得最多num1.length()* num2.length()的结果。

Your code can produce results greater than the string length because of characters that appear more than once in your strings. You can get results of up to num1.length() * num2.length().

如果您想获得具有相同数量的仓位数量两个字符串中的字符,只需一个循环即可,并对两个字符串上的charAt调用使用相同的索引:

In case you want to get the number of positions at which you have the same character in both strings, you can to that in just one loop and use the same index for the "charAt" calls on both strings:

for(int i = 0; i < num1.length() && i < num2.length(); i++) {
    if(num1.charAt(i) == num2.charAt(i)){
        count++;
    }
}

如果你想得到独特字母的数量出现在两个字符串中的,独立地运行两个字符串并将字母添加到集合中。然后相交两组。结果集中的元素数量是您的结果:

In case you want to get the number of unique letters that appear in both strings, run through both strings independently and add the letters to a set. Then intersect both sets. The number of elements in that intersection set is your result:

    Set<Character> characters1 = new TreeSet<Character>();
    for(int i = 0; i < num1.length(); i++) {
        characters1.add(num1.charAt(i));
    }

    Set<Character> characters2 = new TreeSet<Character>();
    for(int i = 0; i < num2.length(); i++) {
        characters2.add(num2.charAt(i));
    }

    characters1.retainAll(characters2);
    return characters1.size();

这篇关于接受2个字符串并在其中显示常用字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆