首页 > 代码库 > C# Split方法

C# Split方法

String.Split 方法有6个重载函数:

1) public string[] Split(params char[] separator)
2) public string[] Split(char[] separator, int count)
3) public string[] Split(char[] separator, StringSplitOptions options)
4) public string[] Split(string[] separator, StringSplitOptions options)
5) public string[] Split(char[] separator, int count, StringSplitOptions options)
6) public string[] Split(string[] separator, int count, StringSplitOptions options)


下边我们通过一些实例来说明下怎么使用(以下string words = "1,2.3,,4";):

1. public string[] Split(params char[] separator)--把字符串按字符数组的内容分割,全部显示出来

string[] split = words.Split(new Char[] { ‘,‘ });//返回:{"1","2.3","","4"}
string[] split = words.Split(new Char[] { ‘,‘, ‘.‘ });//返回:{"1","2","3","","4"}


2. public string[] Split(char[] separator, int count)--把字符串按字符数组的内容分割,分割成count个,然后再完整的显示出来

string[] split = words.Split(new Char[] { ‘,‘, ‘.‘ }, 2);//返回:{"1","2.3,,4"}
string[] split = words.Split(new Char[] { ‘,‘, ‘.‘ }, 6);//返回:{"1","2","3","","4"}


3. public string[] Split(char[] separator, StringSplitOptions options)--把字符串按字符数组的内容分割,判定是否保留空元素。

string[] split = words.Split(new Char[] { ‘,‘, ‘.‘ }, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2","3","4"} 不保留空元素
string[] split = words.Split(new Char[] { ‘,‘, ‘.‘ }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素


4. public string[] Split(string[] separator, StringSplitOptions options)--把字符串按字符串数组的内容分割,判定是否保留空元素。保留None,不保留RemoveEmptyEntries

string[] split = words.Split(new string[] { ",", "." }, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2","3","4"} 不保留空元素
string[] split = words.Split(new string[] { ",", "." }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素


5. public string[] Split(char[] separator, int count, StringSplitOptions options)

string[] split = words.Split(new Char[] { ‘,‘, ‘.‘ }, 2, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2.3,,4"} 不保留空元素
string[] split = words.Split(new Char[] { ‘,‘, ‘.‘ }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素


6. public string[] Split(string[] separator, int count, StringSplitOptions options)把字符串按字符串数组内容分割,分割成count个,判定是否保留空元素

string[] split = words.Split(new string[] { ",", "." }, 2, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2.3,,4"} 不保留空元素
string[] split = words.Split(new string[] { ",", "." }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素

C# Split方法