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

1

12

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.

Bergmans answered 9/10, 2013 at 9:23 Comment(1)
+1, good question. I know how to do this, but it wouldn't be elegant, so until I work out a way this could be done concisely (using something like LINQ) I'll wait to see other suggestions. EDIT: Sorted, there's a method for this.Engorge
E
19

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[] { '+', '-', '/', '*' })];
Engorge answered 9/10, 2013 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.