• Post Reply Bookmark Topic Watch Topic
  • New Topic

String contains function problem  RSS feed

 
Milan Djukic
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why this not works?

if(myString.contain("-"))

??
 
James Sabre
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe because the String class has no method called contain()! The Javadoc is your friend.
 
Milan Djukic
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my bad, contains. Syntax is ok but function not works.

This way works:

 
James Sabre
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is silly! All that code to deal with a spelling error!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean by "it doesn't work"? Does it compile (when you correct the spelling error)? Does it run? Is the output different from what you expect?
 
kumarjit banerjee
Ranch Hand
Posts: 32
Eclipse IDE Oracle Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:What do you mean by "it doesn't work"? Does it compile (when you correct the spelling error)? Does it run? Is the output different from what you expect?



Apart from the spelling, if you are working in jdk1.4 the String class would not contain the contains() method so your code will not compile. If you are using jdk1.5 then your code will compile but you try to run the class file in jdk1.4 it will not run.



So instead of writing

if(s.contains('-'))

you can write

if(s.indexOf(""+'-') > -1)
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kumarjit banerjee wrote:if(s.indexOf(""+'-') > -1)

Why the extra complication of writing: "" + '-'

Just do this:
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or slightly faster: String has two sets of indexOf methods; one that takes a String and one that takes a single char. The latter is somewhat faster since it only needs to look at one char at a time, needing only a simple loop internally. Finding a String requires a bit more work, although with a one-char String the difference is probably minimal. Still, I prefer simplicity.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!