简体   繁体   English

C#使用多个分隔符分割字符串

[英]C# splitting a string with multiple seperator

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 谢谢

您可以使用带多个分隔符的重载:

myString.Split(new[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries);

No need for a regex. 无需正则表达式。 The split method can take a list of separators split方法可以使用分隔符列表

"user1;user2;user3;user4 user1".Split(';', ' ')

outputs 输出

string[5] { "user1", "user2", "user3", "user4", "user1" }

You can use the regex 您可以使用正则表达式

"[ ;]"

the square brackets define a character class - matches one of the characters between the brackets. 方括号定义字符类 -匹配方括号之间的字符之一。

You can use overload of Split() method which take an array of seperator 您可以使用Split()方法的重载,该方法采用分隔符数组

string myString = "user1;user2;user3;user4 user1";
string[] stringSeparators = new string[] { ";", " " };
string[] s = myString.Split(stringSeparators, StringSplitOptions.None);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM