giannisf
giannisf

Reputation: 2599

Correct way to check if a word is the last

I have a string with some text, for example:

var txt = "this is an example";

How can I check if a given word is the last ? Currently I am checking with try catch

try 
  {
     var index = txt.indexOf(word);
     var dummy = txt[index + word.Length-1];
  }

catch(IndexOutOfRangeException ex) {
        // do work
  }

Upvotes: 0

Views: 46

Answers (1)

Marcin Kolny
Marcin Kolny

Reputation: 633

var txt = "this is an example";
if (txt.Split (new []{ ' ' }).LastOrDefault ().Equals (word)) {
   // equals
}

I assume, that word is not empty. And your method, a little bit improved:

if (txt.LastIndexOf(word) == txt.Length - word.Length) {
  // equals         
}

Upvotes: 2

Related Questions