| Author |
How to find occurence of substring in a String?
|
raj malhotra
Ranch Hand
Joined: Feb 22, 2007
Posts: 285
|
|
Hi friends How can i find the occurence a specific string in another String.I know pattern matching is one way. But I want to know the direct way to do it. Thanks in advance
|
 |
bart zagers
Ranch Hand
Joined: Feb 05, 2003
Posts: 234
|
|
|
The String class has the indexOf (and lastIndexOf) method for this.
|
 |
raj malhotra
Ranch Hand
Joined: Feb 22, 2007
Posts: 285
|
|
Hi Bart Thanks for reply .you are right indexOf() is used to find the occurence i just wanted to know total occurrence of a substring in a string. I guess using indexOF with some logic in a loop will work.Is there any other way
|
 |
Maneesh Godbole
Saloon Keeper
Joined: Jul 26, 2007
Posts: 8566
|
|
Originally posted by raj malhotra: Hi friends How can i find the occurence a specific string in another String.I know pattern matching is one way. But I want to know the direct way to do it. Thanks in advance
You can try using the StringTokenizer and call the countTokens or use the split(String regex) in the String class. The split method will return you a String array whose length you can access. In both the cases the result will be the number of tokens/array length -1.
|
[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Originally posted by Maneesh Godbole: You can try using the StringTokenizer and call the countTokens
Note that StringTokenizer only uses single characters as delimiters. If you are looking for a multicharacter string, it won't work.
|
Joanne
|
 |
bart zagers
Ranch Hand
Joined: Feb 05, 2003
Posts: 234
|
|
Your first option is indeed using the indexOf method (the one with two arguments) and use some looping. A second option is using the String.split(1.5+) method and count the tokens. (It works a little different from the StringTokenizer, which indeed will not work). I have no idea what would be the "best" option, but I think I would go for the first option. Another option you have when you would happen to use the Apache Commons Lang project. Their StringUtils class has a countMatches method, which does the trick for you.
|
 |
raj malhotra
Ranch Hand
Joined: Feb 22, 2007
Posts: 285
|
|
|
Thanks you all for reply to sum up the various ways to solve it.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
Originally posted by bart zagers: A second option is using the String.split(1.5+) method...
Actually, String.split is 1.4+
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
bart zagers
Ranch Hand
Joined: Feb 05, 2003
Posts: 234
|
|
Originally posted by Rob Prime: Actually, String.split is 1.4+
Thanks
|
 |
 |
|
|
subject: How to find occurence of substring in a String?
|
|
|