字符串是通過Split方法來實現。有多種重載形式。
格式:字符串1.Split(字符或字符數組),分(fēn)割後返回值是一(yī)個字符串數組。
string mystr = "str1-str2-str3=str4";
string[] spstr = mystr.Split('-');//分(fēn)割字符
foreach(string outstr in spstr)
{
Console.WriteLine(outstr);
}
string[] spstr=mystr.Split(new char[]{'-','='});//分(fēn)割字符數組
foreach (string outstr in spstr)
{
Console.WriteLine(outstr);
}
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)
下(xià)邊我(wǒ)(wǒ)們通過一(yī)些實例來說明下(xià)怎麽使用
(我(wǒ)(wǒ)們定義一(yī)個 字符串 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"} 保留空元素