Hi there,

I'm writing a function to compare strings from two lists, but I'm facing problems comparing the two strings in an easy straightforward way due to my lack of knowledge in Java. I use Python more often which is way easier than Java in string manipulation and comparison.

My code:

for (String s1 : list1){
            for (String s2 : list2){
                if (s1.compareTo(s2) > 0){
                    return true;
                }
            }
        }
        return false;

Basically, what I'm trying to do is this :
I want to know if for example : "M10" is in "MW10-12" which it is, and should return true. Another example: "F9-11" is in "MW10-12" which it is not, and should return false.

So my question is: How do I compare such strings in a smooth way without having to split them in to char[] or String[]....

Thank you for your help!

compareTo returns -1, +1, or 0 depending on whether the string sorts before or after, or is exactly equal to the other string. You're testing for +1, so that's why you get false "equals". To see if one sting occurs inside another one, use String.indexOf(String), which returns the index where the second string starts in the first, or -1 if it's not present.

compareTo returns -1, +1, or 0 depending on whether the string sorts before or after, or is exactly equal to the other string. You're testing for +1, so that's why you get false "equals". To see if one sting occurs inside another one, use String.indexOf(String), which returns the index where the second string starts in the first, or -1 if it's not present.

You cannot use String.indexOf(String) since original request was

"M10" is in "MW10-12" which it is, and should return true. Another example: "F9-11" is in "MW10-12" which it is not, and should return false.

You may consider using String.indexOf(String) if you will work with strings and not with character combination like was requested

This article has been dead for over six months. Start a new discussion instead.