How to find the last occurrence of a set of characters from a string

mega6382 picture mega6382 · Oct 9, 2013 · Viewed 17.6k times · Source

I'm trying to find the last operator (+, -, * or /) in a string.

I was trying to use the method string.indexof('operator', i);, but in this case I could only get the single type of operator. Is there any better solution for this?

The value of string could, for example, be:

1+1/2*3-4

or

1/2-3+4*7

It means the last operator could be any of them.

Answer

user1017882 picture user1017882 · Oct 9, 2013

http://msdn.microsoft.com/en-us/library/system.string.lastindexofany.aspx

The LastIndexOfAny method is what you're after. It will take an array of characters, and find the last occurrence of any of the characters.

var myString = "1/2-3+4*7";
var lastOperatorIndex = myString.LastIndexOfAny(new char[] { '+', '-', '/', '*' });

In this scenario, lastOperatorIndex == 7

If you're wanting to store the char itself to a variable you could have:

var myString = "1/2-3+4*7";
var operatorChar = myString[myString.LastIndexOfAny(new char[] { '+', '-', '/', '*' })];