Results 1 to 8 of 8
  1. #1
    hilather is offline Member
    Join Date
    Nov 2008
    Posts
    2
    Rep Power
    0

    Default Problem Comparing Strings (its not what you think)

    I'm not sure if I'm posting in the right place, I'm not all that new to Java, but I'm surely looking for some newbish help. I have a program that looks like something like this...
    Java Code:
    for (int i = 0; i < SMSArray.size(); i++)
    {
                String [] smsSplit = SMSArray.get(i).getSearchString().toString().split(" ");
                //System.out.println(SMSArray.get(i).getSearchString().toString());
                for (int x =0; x < data.getList().size(); x++)
                {
                    String [] dataSplit = data.getList().get(x).getName().toString().split(" ");
                    //if (data.getList().get(x).getName().startsWith(SMSArray.get(i).getSearchString()))
                    if (smsSplit.length == 1)
                    {
                        if (dataSplit[0].toLowerCase().contains(smsSplit[0].toLowerCase()))        
                        {
                            SMSArray.get(i).Array.add(data.getList().get(x).toString());
                            System.out.println("MATCH");
                        }       
                   }
    }
    The problem is this line
    if (dataSplit[0].toLowerCase().contains(smsSplit[0].toLowerCase()))

    This works, using the contains method, however if I use the startsWith or equals method it always returns false, even though there are a lot of strings that match. I've tried equalsignore case and all that jazz, I've even tried trimming the variables as well (even though I know there is no trailing white space.)

    Can anyone elaborate on why the contains method might work and the equals method will not? I have a feeling I'm overlooking something small. Ideally I'd like to be using the startsWith method, but contains is working for me now, it just produces some false positives that I'm not all too concerned with.

    I tried googling this, all I get is stuff about the equals method vs == which is an obvious no brainer.

  2. #2
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    You check out the String API? There's a method there that makes your job a whole lot easier.

  3. #3
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    Equals goes for exact match, in totality.
    Java Code:
    String s = new String("Hot puppies for sale, cheap.");
    // Not the same.
    String t = new String("Hot puppies for sale - cheap.");
    if(s.contains("Hot licks");// will fail.
    if(t.contains("Hot licks");// will fail.
    if(s.equals("Hot")){print something();}// will fail.
    dot equals considers all of both strings, as directed - read docs.

    I unpacked src.zip and read sources along with comments, makes the day go on.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  4. #4
    fishtoprecords's Avatar
    fishtoprecords is offline Senior Member
    Join Date
    Jun 2008
    Posts
    571
    Rep Power
    7

    Default

    Quote Originally Posted by Nicholas Jordan View Post
    Equals goes for exact match, in totality.
    Actually, since String objects are immutable, and the JVM does common constant folding, often for a String, .equals() is the same as ==.

    Not always, and you should not rely on it, but its usually true.

    This is not true in general, there is a reason that there are both == and .equals()

  5. #5
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Quote Originally Posted by fishtoprecords View Post
    Actually, since String objects are immutable, and the JVM does common constant folding, often for a String, .equals() is the same as ==.

    Not always, and you should not rely on it, but its usually true.
    No, not even close to always, not even close to usually. It only works for String literals, or for two String variables whose references have both been defined using the same String reference.

    i.e.
    Java Code:
    String a = "1";
    String b = "1";
    if (a == b)
    // and
    if (a.equals(b))
    // are both true
    String c = bufferedReader.readLine();
    String a = c;
    String b = c;
    if (a == b)
    // and
    if (a.equals(b))
    // are both true
    For Strings defined any other way, it is not true.
    i.e.
    Java Code:
    bufferedReader.mark();
    String a = bufferedReader.readLine();
    bufferedReader.reset();
    String b = bufferedReader.readLine();
    if (a == b)
    // and
    if (a.equals(b))
    // are not both true even though both contain the exact same sequence read from the exact same Reader.
    And if those first two ways are the majority of a programs String assignments, then I feel something is generally wrong. At the very least it means the program gets, essentially, no "real" input from anywhere. For some specific things, this is probably more than ok, but for most programs? I don't think so.
    Last edited by masijade; 11-15-2008 at 10:26 AM.

  6. #6
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    @OP, try this, to make sure that you're seeing what you think you are seeing:

    Java Code:
        if (dataSplit[0].equalsIgnoreCase(smsSplit[0])) {
            SMSArray.get(i).Array.add(data.getList().get(x).toString());
            System.out.println("MATCH");
        } else if (dataSplit[0].toLowerCase().contains(smsSplit[0].toLowerCase())) {
            System.err.print("equals failed but contains matches.  data String: ");
            System.err.print(dataSplit[0].length()) + " ---");
            System.err.print(dataSplit[0]);
            System.err.print("---  sms String: ");
            System.err.print(smsSplit[0].length()) + " ---");
            System.err.print(smsSplit[0]);
            System.err.println("---");
        }
    The length and "---" sequences are there for a reason. The "---" to catch any whitespace, and the lengths to catch non-printable characters that the PrintStream, or the console, might swallow. Now, if they both have the same number of non-printable characters, but located at different spots on the String, those won't be caught, you'll have to print the individual byte values to catch those.

  7. #7
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Talking constant folding and loop invariant lifting

    Quote Originally Posted by fishtoprecords View Post
    Actually, since String objects are immutable, and the JVM does common constant folding, often for a String, .equals() is the same as ==.

    Not always, and you should not rely on it, but its usually true.

    This is not true in general, there is a reason that there are both == and .equals()
    This would be one of those things I would suggest Andre examine. ftr's my favorite of all the web so it pains me to try to crawl through this, but as observed by masijade, two new's { or return from method call as he shows } would likely get false on if(s1 == s2) and, as you state, we don't really have any truetest as portability and compiler science render masijade's observation of greater utility.

    Sorta reminds me of the Train Schedule and some issues of using char[] pw = String.getChars(); not being reliable either because of L-2 writebacks being at the mercy of the os. Opie posted on getting SMS so we really will go off the deep end if there are funny characters sms'ing at Fog Horn Train Station......

    ( humor folks, these two can deal with it and move on ... )

    For now, I am going to bury my hopes in css and xhtml to get printable at the browser, be though it may I dread issues just such as this lurking in the leepoints. I spend way too much time waiting for Notepad to init() so that I can remove embedded scripting characters and still wish for the day I can lift all non-printable from the copy-paste buffer with simple clicks.

    Rue the day Online Banking is done from PDA's - no?...
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  8. #8
    hilather is offline Member
    Join Date
    Nov 2008
    Posts
    2
    Rep Power
    0

    Default

    Thanks for the advice guys, I'll try some testing with masijade's code.

    I'm aware of the exact nature .equals() works, and I'm also aware that these strings should match up no problem. Which is why this issue has confused me. I'll play around with it and when I figure out what I'm doing wrong I'll post back.

Similar Threads

  1. Comparing Strings
    By souFrag in forum Advanced Java
    Replies: 5
    Last Post: 05-21-2008, 09:03 AM
  2. JSTL -- Comparing two strings for equality
    By trinkets in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 02-12-2008, 04:39 PM
  3. Comparing null problem
    By thirdy_veritech in forum New To Java
    Replies: 2
    Last Post: 02-06-2008, 08:46 AM
  4. Comparing problem
    By mcal in forum New To Java
    Replies: 1
    Last Post: 01-24-2008, 03:56 AM
  5. Comparing Strings
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-03-2007, 09:44 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •