如何比较两个不同长度的字符串来查找相同的子字符串

时间:2016-03-09 12:05:36

标签: java arrays string

问题是: 客户帐户使用代码(例如MA400)在分类系统下提交。我需要一种方法将原始MA400重置为更新的代码,如MA400.4。如果新代码有5个字符,原始复位,则该方法返回true。不是最好的措辞,但这就是我现在所拥有的。

如果角色需要处于相同的顺序,则没有指定,例如。

    String str = "abc123";
    String newStr = "xyz123abc";

我假设他们需要处于相同的顺序。所以上面的字符串只有3个相似的字符。

    char[]array = str.toCharArray();
    char[]array2 = newStr.toCharArray();

我现在想在两个数组上使用compareTo方法,但我不确定这是如何工作的。也许我可以使用for循环来停止在最短字符串中的最后一个元素之后进行比较,但不完全确定我是否可以做很多事情。

我觉得我是以错误的方式解决这个问题而且有一种不那么复杂的方法来检查字符串中的相似字符?

1 个答案:

答案 0 :(得分:2)

据我所知,这样的事情会起作用。请记住,这只会计算唯一字符。订单无关紧要

public static boolean matchingChar(final String st1, final String st2) {

        if(st1 == null || st2 == null || st1.length() < 5  || st2.length() < 5) {
            return false;
        } 

        //This is if you wish unique characters to be counted only
        //Otherwise you can use simple int count = 0
        HashSet<Character> found = new HashSet<Character>();

        //found.size() < 5 so the loop break as soon as the condition is met
        for(int i = 0; i < st1.length() && found.size() < 5; i++) {         
            if(st2.indexOf(st1.charAt(i)) != -1) {
                found.add(st1.charAt(i));
            }
        }

        return found.size() >= 5;
    }
相关问题