0
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

3
  • @Mostafiz Why did you removed the new line? Commented Aug 21, 2016 at 10:08
  • ops question have no newline its space I think Commented Aug 21, 2016 at 10:10
  • @Mostafiz look at the previous edit diff, it's indeed a new line ;) Commented Aug 21, 2016 at 10:51

5 Answers 5

3

You can use overload taking multiple separators:

myString.Split(new[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries);
Sign up to request clarification or add additional context in comments.

Comments

1

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" }

Comments

0

You can use the regex

"[ ;]"

the square brackets define a character class - matches one of the characters between the brackets.

Comments

0

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);

Comments

0

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));
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.