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!

Recommended Answers

All 4 Replies

You don't want to compare string in this case. You need to run regular expressions. Have look at this Regular Expressions tutorial from Sun

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

Ooops! Yes, you're right. I missed the "W" when I read the OP. Sorry.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.