String.Split()函数

String.Split()

用法为:       

   string[] ss1 = s.Split(new[] {"|:|"}, StringSplitOptions.None);
            //ss1[0]: A|B
            //ss1[1]: C:D
后一个参数 是标志是否自动 remove empty 的数据 例如 :  "A|B|:|C:D|:|"   做分割时 会返回三个数组 该数组的最后一个元素是空 "" 如果我们想过滤掉这些空的元素 可以使用参数 :  StringSplitOptions .RemoveEmptyEntries   string [] ss1s.Split(new[] {"|:|"}, StringSplitOptions.RemoveEmptyEntries);  
例子 :          
            s = "A|B|:|C:D|:|";
            string[] ss1 = s.Split(new[] {"|:|"}, StringSplitOptions.RemoveEmptyEntries);
            //ss1[0]: "A|B"
            //ss1[1]: "C:D"

            ss1 = s.Split(new[] { "|:|" }, StringSplitOptions.None);
            //ss1[0]: "A|B"
            //ss1[1]: "C:D"
            //ss1[2]: ""

首先我们看下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)
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)
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)
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"} 保留空元素

你可能感兴趣的:(String.Split()函数)