Code Junkie
Code Junkie

Reputation: 7788

Parse phrase with indexof and then get beginning of word

I have a phrase and a keyword. I'm trying to find the first indexof the keyword, but then get the whole word containing it. How do I get the whole word? The problem is the keyword might be text within the a word.

Example

String keyword = "wor";

String phrase = "my keyword search phrase";

I'd like to return "keyword search phrase"

I tried phrase.indexOf(keyword);

but I naturally get "word search phrase"

Upvotes: 0

Views: 432

Answers (3)

RealSkeptic
RealSkeptic

Reputation: 34628

Personally, I prefer regular expressions, because then you can check for a word even if it was separated by something other than a space, like a tab character.

    String keyword = "wor";

    String phrase = "my keyword search phrase\twor";

    Pattern p = Pattern.compile("\\b" + keyword + "\\b");

    Matcher m = p.matcher(phrase);

    int i = 0;
    if ( m.find()) {
        i = m.start();
    }

Upvotes: 1

Mureinik
Mureinik

Reputation: 311393

You can use phrase.indexOf(keyword) and backtrack to the last space before it:

String keyword = "wor";
String phrase = "my keyword search phrase";
int keywordIndex = phrase.indexOf(keyword);
int lastSpaceIndex = phrase.substring(0, keywordIndex).lastIndexOf(' ');
return phrase.substring(lastSpaceIndex + 1);

Upvotes: 2

SMA
SMA

Reputation: 37023

Try this:

String keyword = "wor";
String phrase = "my keyword search phrase";
int keywordsIndex = phrase.indexOf(keyword);
int spaceIndex = phrase.substring(0, keywordsIndex).lastIndexOf(' ');
System.out.println (phrase.substring(spaceIndex + 1));

Upvotes: 2

Related Questions