单个字符隔开
实例:
页面代码:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
</body>
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string[] split = TextBox1.Text.Split(new Char[] { ',' });
//获取文本以逗号隔开的值个数(例如:张三,李四)那么split.Length.ToString()==2
TextBox2.Text=split.Length.ToString();
//获取第一个值(如张三)
TextBox3.Text=split[0].ToString();
//获取第二个值(如李四)
TextBox4.Text=split[1].ToString();
}
当文本框里输入的结果是“张三,”这时系统会默认有一个空值,也就是说都好分割开的个数是2;那么我们应该如何忽略这个空值呢?
string[] split = TextBox1.Text.Split(new Char[] { ',' },StringSplitOptions.RemoveEmptyEntries);
//加上这么一句话StringSplitOptions.RemoveEmptyEntries就可以了!
//(例如:张三,)split.Length.ToString()的值为1
用多个字符来分隔:
string time="10时48分66秒";
string[] split = time.Split(new Char[] { '时', '分', '秒' }); string hour = split[0].ToString(); string min = split[1].ToString(); string ss = split[2].ToString();
//求的秒数 int second = int.Parse(hour) * 3600 + int.Parse(min)*60 + int.Parse(ss);