描述:返回一个下标从0开始的一维数组,它包含指定数目的子字符串
实例:
1.用单个字符分隔
string str1 = "1,2,3";
string [] str = str1.split(','); //得到:{"1","2","3"}
foreach(string s in str){
Response.Write( s+"<br/>");
}
输出结果://1
//2
//3
2.用多个字符分隔
string str1 = "1,2,3.4"
string str2 = str1.split(new char[2]{',','.'});
foreach(string s in str2){
Response.Write(s+"<br/>");
}
输出结果://1
//2
//3
//4
3.用字符串分隔
using System.Text.RegularExpressions;
string str="aaajsbbbjsccc";
string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);
foreach (string i in sArray) {
Response.Write(i.ToString() + "<br>");
}
输出结果:
aaa
bbb
ccc
总结提高:
string[] arr = str.Split("o");
这是一个具有语法错误的语句,Split 的 separator参数应该是 char[] 或 string[],不应是字符串。正确的示例:
string str = "technology";
char[] separator = { 'o' };
string[] arr = str.Split(separator);
String.Split 方法有6个重载函数:以下string str= "1,2.3,,4";
- public string[] Split(params char[] separator)
string[] split = str.Split(new Char[] { ',' });//返回:{"1","2.3","","4"}
string[] split = str.Split(new Char[] { ',', '.' });//返回:{"1","2","3","","4"}
- public string[] Split(char[] separator, int count)
string[] split = str.Split(new Char[] { ',', '.' }, 2);//返回:{"1","2.3,,4"}
string[] split = str.Split(new Char[] { ',', '.' }, 6);//返回:{"1","2","3","","4"}
- public string[] Split(char[] separator, StringSplitOptions options)
string[] split = str.Split(new Char[] { ',', '.' }, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2","3","4"} 不保留空元素
string[] split = str.Split(new Char[] { ',', '.' }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
- public string[] Split(string[] separator, StringSplitOptions options)
string[] split = str.Split(new string[] { ",", "." }, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2","3","4"} 不保留空元素
string[] split = str.Split(new string[] { ",", "." }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
- public string[] Split(char[] separator, int count, StringSplitOptions options)
string[] split = str.Split(new Char[] { ',', '.' }, 2, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2.3,,4"} 不保留空元素
string[] split = str.Split(new Char[] { ',', '.' }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
- public string[] Split(string[] separator, int count, StringSplitOptions options)
string[] split = str.Split(new string[] { ",", "." }, 2, StringSplitOptions.RemoveEmptyEntries);//返回:{"1","2.3,,4"} 不保留空元素
string[] split = str.Split(new string[] { ",", "." }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素