2

I have two strings to compare

String st1 = "database-2.0/version\"25-00\"";
String st2 = "database2.0version25";

I want to determine if st1 contains st2. In the example provided I expect to get Yes as answer because the order of characters in st2 is same is st1 and it only missing some characters. Is any function in Java library to do such comparison? I am aware of st1.indexOf(st2) and st1.contains(st2) but they didn't work in this case, both returned false.

3
  • just remove all characters in the first string that you don't care about like / and " and so on then just do st1.contains(st2) Commented Nov 28, 2017 at 19:22
  • yeah sure, just was wondering if there was a library or function doing this. thanks though Commented Nov 28, 2017 at 19:25
  • Joseph Ryle is correct, this is a subsequence. See: geeksforgeeks.org/… Commented Nov 28, 2017 at 23:04

3 Answers 3

2

Try this:

String regex = st2.chars()
                  .mapToObj(i -> String.valueOf((char) i))
                  .map(str -> ".*+?^${}()|[]\\".contains(str) ? "\\" + str : str)
                  .collect(Collectors.joining(".*", ".*", ".*"));

boolean contains = st1.matches(regex);

Here's a rundown:

  • Get a regex string of the shorter string (st2 in our case - hardcoded - you can automate this of-course), adding .* in front and back, and between each character. (.* matches 0 or more of any character).

  • String.chars() returns an IntStream, convert it to String with type cast

  • As @Robert suggested, escape special characters with a backslash.

  • Check of the longer string matches, which effectivelly means it contains all characters of the short string, and maybe more.

Sign up to request clarification or add additional context in comments.

5 Comments

thank you. Can you explain a bit more I am new to Java, a bit confused on what your code does.
What if the string has characters that have special meanings in regular expressions?
@Robert: Could you bring some example?
@MouseEvent, thanks it is working, also thanks for explanation
@Robert Oops... Will add backslashes all over.
0

What you are looking for is a subsequence, not a substring.

Here's a working solution I found on geeksforgeeks:

// Recursive Java program to check if a string
// is subsequence of another string
import java.io.*;

class SubSequence
{
    // Returns true if str1[] is a subsequence of str2[]
    // m is length of str1 and n is length of str2
    static boolean isSubSequence(String str1, String str2, int m, int n)
    {
        // Base Cases
        if (m == 0) 
            return true;
        if (n == 0) 
            return false;

        // If last characters of two strings are matching
        if (str1.charAt(m-1) == str2.charAt(n-1))
            return isSubSequence(str1, str2, m-1, n-1);

        // If last characters are not matching
        return isSubSequence(str1, str2, m, n-1);
    }

    // Driver program
    public static void main (String[] args) 
    {
        String str1 = "database2.0version25";
        String str2 = "database2.0/version\"2-00\"";
        int m = str1.length();
        int n = str2.length();
        boolean res = isSubSequence(str1, str2, m, n);
        if(res)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

// Contributed by Pramod Kumar

2 Comments

Copying code from other ages may be an intellectual property violation issue.
@Robert Reference is complete with text location and author credit, and this redistribution meets the criteria set forth by CC.
0

You can find the subsequence needle in the string haystack by looking for needle's characters in order, starting from an index searchFrom that you update as you find each successive character.

In the following code, note that haystack.indexOf(needleChar, searchFrom) returns the index of the first occurrence of needleChar starting from index searchFrom in haystack.

boolean contains(String haystack, String needle) {
    int searchFrom = 0;
    for (char needleChar : needle.toCharArray()) {
        searchFrom = haystack.indexOf(needleChar, searchFrom);
        if (searchFrom == -1) {
            return false;
        }
    }
    return true;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.