Reputation: 786
user1;user2;user3;user4 user1
I'd like to split these strings so I can iterate over all of them to put them in objects. I figured I could use
myString.split(";")
However, in the second example, there is no ; , so that wouldn't do the trick. What would be the best way to do this when it can be variable like this?
Thanks
Upvotes: 0
Views: 78
Reputation: 1703
the following test pass!
[TestCase("user1;user2;user3;user4 user1", 5)]
public void SplitString(string input, int expectedCount)
{
Assert.AreEqual(expectedCount, input.Split(new []{";"," "},StringSplitOptions.RemoveEmptyEntries));
}
Upvotes: 0
Reputation: 7352
You can use overload of Split()
method which take an array of seperator
string myString = "user1;user2;user3;user4 user1";
string[] stringSeparators = new string[] { ";", " " };
string[] s = myString.Split(stringSeparators, StringSplitOptions.None);
Upvotes: 0
Reputation: 23551
No need for a regex. The split method can take a list of separators
"user1;user2;user3;user4 user1".Split(';', ' ')
outputs
string[5] { "user1", "user2", "user3", "user4", "user1" }
Upvotes: 1
Reputation: 37918
You can use overload taking multiple separators:
myString.Split(new[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries);
Upvotes: 3
Reputation: 21470
You can use the regex
"[ ;]"
the square brackets define a character class - matches one of the characters between the brackets.
Upvotes: 0