java - How to find occurrence of a string in another string where it's not embedded into another word? -


I am trying to create a static method "indexOfKeyword" and return an index for a string where string is the other word Has not been embedded in. If there is no such incident then -1 will return.

For example,

  string s = "In Florida, snowshoes do not create any interest."; String keyword = "no";  

This will return 31.

I think the only problem is not to find the next occurrence of the string keyword. What I've done so far:

  Public static integeroffkeyword (string s, string keyword) {s = s.toLowerCase (); Keyword = keyword.toLowerCase (); Int startIdx = s.indexOf (keyword); While (startIdx> = 0) {string = ""; = "" String after; If (startIdx> 0) {before ssubstring (startIdx - 1, startIdx); } Int endIdx = startIdx; If (endIdx & lt; s.length ()) followed by {s.sstring (startIdx + keyword.length (), startIdx + keyword.length () + 1); } If (((before ((before () (= "A") gt0 = amp; amp; amp; before.compareTo ("z") & lt; = 0 & amp; amp; amp; after.compareTo (" A ")> = 0 & amp;; Amp; after.compareTo (" z ") & lt; = 0)) {return startIdx; } StartIdx = / * expression to start the next occurrence of the 2-input index; Return -1; } Public static zero main (string [] args) {// ... and test string here = ""; String keyword = ""; System.out.println (indexOfKeyword (keyword));  

Something like this:

  string input = "In Florida, snowshoes do not cause any interest."; String pattern = "\\ bno \\ b"; Matcher matcher = Pattern.compile (pattern) .Misper (input); Return matcher.find ()? Matcher.start (): -1;  

Strings in other words are not embedded, they are not delimited by spaces. It can be a comma, duration, start of string, and so on.

The above solution uses the regular expression word bounds ( \ b ) to give the correct solution.

  string pattern = "\">  

\ B "+ pattern. Quote (keyword) +" \\ b ";

then a complete method implementation might look like this:

  public static int indexOfKeyword (string s, string keyword) {string pattern = "\\ b" + pattern. (Keyword) + "\\ b"; Matcher matcher = Pattern.compile (pattern) .missher (s); return matcher.find ()? Matcher.start (): -1;}  

Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -