繁体   English   中英

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

[英]How to compare two strings, of different length to find identical substring

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

是否需要指定字符的相同顺序,例如未指定。

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

我假设它们需要保持相同的顺序。 因此,以上字符串仅包含3个类似的字符。

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

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

我觉得我正在以错误的方式进行此操作,并且有一种更简单的方法来检查字符串中的相似字符?

据我了解,类似的东西会起作用。 请记住,这只会计算唯一字符。 顺序没关系

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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