Link to home
Start Free TrialLog in
Avatar of ezpete
ezpete

asked on

NextWord type function

Hello,

I am looking for a function that will return the next word in a string when given a keyword and number that reflects the occurrence of that keyword in the string sort of like this.

NextWord('keyword', 'orginal_string', nth_occurrence_of_keyword);

Example: NextWord('home', 'You have a lovely home Mr Smith. I hope to have a home like this someday',  2);  

In the above example the word that I would like to return is "like" because it is the next word after the 2nd occurrence of the word home

Can anyone help me with this ?

Thanks,
Ezpete.
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

This should do the trick
function NextWord(Keyword, OriginalString: String; Occurrence: Integer): String;
var
List: Tstrings;
i, x: Integer;
begin
   result := '';
   x := 0;
   List := TStringList.Create;
   try
      List.Delimiter := ' ';
      List.DelimitedText := OriginalString;
      for i := 0 to List.Count-1 do
      begin
         If List[i] = Keyword then
            begin
               Inc(x);
               If x = Occurrence then
                  begin
                     result := List[i+1];
                     Break;
                  end else continue;
            end;
      end;
   finally
      List.Free;
   end;
   If Result = '' Then Result := 'Not Found';
end;

Open in new window

Avatar of ezpete
ezpete

ASKER

Thanks for the quick reply,  I was just about to head off to bed but thought I would check back here again one more time and you already had a reply which is wonderful so I thank you again for that, anyway I have done some preliminary testing and so far everything is working fine, I will conduct a few more test when I get up and report back on my results and award you the points if everything checks out.

Thanks Again,
Ezpete.
1. You might need to remove some punctuation from the parsed items in the TStringlist.  In this case, I expect that one item will be "Smith."  (note the trailing period)  If you were looking for "smith" you would not match that item.

2. What do you want to happen if there is no next word after the nth occurrence of the word?  If the found nth word is the last word in the string, what do you want to be returned?
ASKER CERTIFIED SOLUTION
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ezpete

ASKER

Thanks again I was having some out of bounds problems as expected but the new function seems to have fixed that and it all looks to be working fine thanks again.