This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes search a sub-string in a string ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "search a sub-string in a string ?" Watch "search a sub-string in a string ?" New topic
Author

search a sub-string in a string ?

Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798
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

Joined: Jul 02, 2002
Posts: 36
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

Joined: Jun 09, 2003
Posts: 4632
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

Joined: Dec 23, 2003
Posts: 798
what is the meaning of "\\b" in the "\\bswing\\b"?

Thanks





Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Take a look at the Pattern class documentation.

Were you able to discover the answer? Or would you like a little bit more nudging?


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
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.
 
 
subject: search a sub-string in a string ?