Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

search a sub-string in a string ?

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to search a sub-string in a string,

for example,

String myString = "java swing buffer";
String target = "swing";

I want to tell if the myString contains "swing" or not ?

Thanks
 
jim gotti
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
maybe use of indexOf(String str) will help? from the API...

[ September 02, 2004: Message edited by: jim gotti ]
[ September 02, 2004: Message edited by: jim gotti ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
indexOf() will work, but it will also 'find' swing in swinging, or airswing etc.

If you want only the word swing, then you might need a method that uses a regex e.g.split()

Something like this perhaps


(edited to add " ", otherwise will not find swing if it is the last word)
[ September 02, 2004: Message edited by: Michael Dunn ]
 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the meaning of "\\b" in the "\\bswing\\b"?

Thanks





 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the Pattern class documentation.

Were you able to discover the answer? Or would you like a little bit more nudging?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might also like to take a look at the two introductory articles I wrote for the JavaRanch Journal on the java.util.regex package. The articles appeared in the September 2002 and April 2003 editions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic