Search code examples
c#stringlastindexof

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


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.


Solution

  • 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[] { '+', '-', '/', '*' })];