Reputation: 1082
I have a string that may contain some forbidden characters like let's say :
char[] BAD_CHARS = new char[] { '-', '.' };
I want strings like "Foo 106.4" to be represented like "Foo 106"
fooString= fooString.Substring(0, fooString.LastIndexOf('-'));
This would be the solution ... but im looking for something more dynamic .
How can I apply this logic above to the BAD_CHARS without doing foreach loops ?
Upvotes: 0
Views: 325
Reputation: 50114
You're pretty close. Assuming you want to stop at the first (not last) bad character,
fooString = fooString.Substring(0, fooString.IndexOfAny(BAD_CHARS));
This has the advantage of not having to process (and split into substrings) the entire input.
Upvotes: 3
Reputation: 1169
You could do it that way with string.Split();
string foostring = "foo 204.5-4";
string[] splitted = foostring.Split(BAD_CHARS);
string result = splitted[0];
Or
string foostring = "foo 204.5-4";
string result = foostring.Split(BAD_CHARS)[0];
You can try it out here
Upvotes: 3