Results 1 to 4 of 4
Like Tree2Likes
  • 1 Post By KevinWorkman
  • 1 Post By jim829

Thread: Compare substring with string?

  1. #1
    Nozz is offline Member
    Join Date
    Apr 2014
    Posts
    49
    Rep Power
    0

    Default Compare substring with string?

    Why isn't it working?
    Java Code:
    					if ((line.substring(i,i+2)) == "go")
    						break;
    I printed this to check if substring works fine, used this:
    Java Code:
    	System.out.println(line.substring(i,i+2) + " : "+ length);
    So, output:
    Er : 1
    ra : 2
    ag : 3
    go : 4
    on : 5
    n' : 6
    '> : 7

    Line:
    String line = "Eragon'>";


    Shouldn't it break loop after printing "go : 4"?
    line.substring(i,i+2) prints go here. But if doesn't work.
    What is wrong?

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,143
    Rep Power
    15

    Default Re: Compare substring with string?

    Don't use == with Strings. Use the equals() method instead. Do a search on this forum or on google for a better explanation of why.
    Nozz likes this.
    How to Ask Questions the Smart Way
    Static Void Games - GameDev tutorials, free Java and JavaScript hosting!
    Static Void Games forum - Come say hello!

  3. #3
    Nozz is offline Member
    Join Date
    Apr 2014
    Posts
    49
    Rep Power
    0

    Default Re: Compare substring with string?

    Well, used charAt instead of substring, but thanks for advice.

    Those two works same:

    Java Code:
    if (line.charAt(i) == '\"')
    if ((line.substring(i,i+1)).equals("\""))

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Compare substring with string?

    That's because in the first case, you are actually comparing a char to a char. For that you may use ==. In the second case you are comparing a String to a String. For that you must use equals.

    Regards,
    Jim
    KevinWorkman likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 2
    Last Post: 04-28-2013, 02:50 AM
  2. how to get substring form a string
    By gvs048 in forum New To Java
    Replies: 4
    Last Post: 04-15-2013, 05:01 PM
  3. How do I remove a substring from a string?
    By Unnel in forum New To Java
    Replies: 16
    Last Post: 07-11-2011, 12:56 PM
  4. Compare substring to char
    By Muskar in forum New To Java
    Replies: 2
    Last Post: 11-21-2010, 09:24 PM
  5. String substring function
    By ravian in forum New To Java
    Replies: 6
    Last Post: 01-02-2008, 08:35 PM

Posting Permissions

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