Tuesday 15 April 2014

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



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

i trying create static method "indexofkeyword" , homecoming indexof string string not embedded word. homecoming -1 if there's no such occurrence.

for example,

string s = "in florida, snowshoes generate no interest."; string keyword = "no";

this homecoming 31.

the problem believe not beingness find next occurrence of string keyword. have far is:

public static int indexofkeyword( string s, string keyword ) { s = s.tolowercase(); keyword = keyword.tolowercase(); int startidx = s.indexof( keyword ); while ( startidx >= 0 ) { string before = " "; string after = " "; if ( startidx > 0 ){ before = s.substring( startidx - 1 , startidx); } int endidx = startidx; if ( endidx < s.length() ){ after = s.substring( startidx + keyword.length() , startidx + keyword.length() + 1); } if ( !(before.compareto("a") >= 0 && before.compareto("z") <= 0 && after.compareto("a") >= 0 && after.compareto("z") <= 0)){ homecoming startidx; } startidx = /* look using 2-input indexof start of next occurrence */ } homecoming -1; } public static void main( string[] args ) { // ... , test here string s = ""; string keyword = ""; system.out.println( indexofkeyword( s, keyword ) ); }

something this:

string input = "in florida, snowshoes generate no interest."; string pattern = "\\bno\\b"; matcher matcher = pattern.compile(pattern).matcher(input); homecoming matcher.find() ? matcher.start() : -1;

strings not embedded in word not delimited spaces. comma's, periods, origin of string, etc.

the above solution uses regular look word boundaries (\b) give right solution.

if there's risk of keyword containing characters have special meaning when used in regular expressions, want escape first:

string pattern = "\\b" + pattern.quote(keyword) + "\\b";

so finish method implementation this:

public static int indexofkeyword(string s, string keyword) { string pattern = "\\b" + pattern.quote(keyword) + "\\b"; matcher matcher = pattern.compile(pattern).matcher(s); homecoming matcher.find() ? matcher.start() : -1; }

java

No comments:

Post a Comment