Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a string backwards to find a character or phrase

Tags:

string

c#

indexof

Is there a good way to start at a given index and move BACKWARDS looking for a given phrase in a string? I only know how to use indexof iterating forwards.

like image 869
Wilson Avatar asked Jan 25 '26 20:01

Wilson


1 Answers

You can use LastIndexOf:

int index = s.LastIndexOf("foo");

It also has an optional start index if you want to start search backwards from somewhere other than the end of the string.

int index = s.LastIndexOf("foo", 20);
like image 145
Mark Byers Avatar answered Jan 28 '26 10:01

Mark Byers