MD_90
MD_90

Reputation: 5

Finding patterns in strings using basic Java methods

say we have a string with these characters "ABGCCFFGTBG"

then we have another string with characters "GECCCDOABG"

So the pattern is the prefix and suffix but if your given strings larger then this but have common prefix and suffix patterns how to pull those out into a substring in java. Keep in mind we dont always know the characters in the string were getting we just know there is a pattern in it.

my start is something like this

for(int i = 0. i < strA.length(); i++)
{
    for(int j = 0; j < strB.length(); j++)
    {
       if(strA.charAt(i) == strB.charAt(j))
       {
          String subPattern = strA.substring(0,i);
          String subPattern2 = strB.substring(0,j);
       }
    }
}  

but this doesn't work. Any ideas?

Upvotes: 0

Views: 103

Answers (2)

ursa
ursa

Reputation: 4611

Try to select best-matched pattern at first:

public static void main(String[] args) {
    String strA = "ABGCCFFGTBG";
    String strB = "GECCCDOABG";
    System.out.println("Pattern: " + findPattern(strA, strB));
}

public static String findPattern(String strA, String strB) {
    for (int length = Math.min(strA.length(), strB.length()); length > 0; length--) {
        for (int i = 0; i <= strA.length() - length; i++) {
            String pattern = strA.substring(i, i + length);
            if (strB.contains(pattern)) {
                return pattern;
            }
        }
    }
    throw new NoSuchElementException("No common pattern between " + strA + " and " + strB);
}

Output:

Pattern: ABG

Upvotes: 1

flis
flis

Reputation: 11

this solution will find a pattern, no matter where it is in the string:

public static void main(String[] args) {

    String strA = "uioABCDqwert";
    String strB = "yxcvABCDwrk";

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < strA.length(); i++) {
        for (int j = 0; j < strB.length(); j++) {
            if (strA.charAt(i) == strB.charAt(j)) {
                sb.append(strB.charAt(j));
                i++;
            }
        }
        if (sb.length() > 0)
            break;
    }

    System.out.println(sb.toString());
}

this should give you an idea how it could be done

Upvotes: 0

Related Questions