简体   繁体   English

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

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

The problem is: Client accounts are filed under a classification system using codes eg MA400. 问题是:客户帐户是使用代码(例如MA400)在分类系统下归档的。 I need a method that will reset the original MA400 to an updated code such as MA400.4. 我需要一种将原始MA400重置为更新代码(例如MA400.4)的方法。 If the new code has 5 characters to which the original is reset then the method returns true. 如果新代码有5个字符,原始代码将重置为5个字符,则该方法返回true。 Not the best wording but that is all I have right now. 不是最好的措辞,但这就是我现在所拥有的。

It hasn't been specified if the characters need to be in the same order, eg. 是否需要指定字符的相同顺序,例如未指定。

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

I am assuming they need to be in the same order. 我假设它们需要保持相同的顺序。 So the above strings would only have 3 like characters. 因此,以上字符串仅包含3个类似的字符。

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

I am thinking now to use a compareTo method on the two arrays, but I am not sure how this would work exactly. 我现在正在考虑在两个数组上使用compareTo方法,但是我不确定这将如何工作。 Perhaps I could use a for loop to stop comparing after the final element in the shortest string but not entirely sure if I can do much with that. 也许我可以使用for循环停止在最短字符串中的最后一个元素之后进行比较,但不能完全确定我是否可以做很多事情。

I feel like I am going about this in the wrong way and there is a less complicated way to check for like characters in a string? 我觉得我正在以错误的方式进行此操作,并且有一种更简单的方法来检查字符串中的相似字符?

From what I understand something like this will work. 据我了解,类似的东西会起作用。 Remember this will only count unique characters. 请记住,这只会计算唯一字符。 Order does not matter 顺序没关系

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