6、Split()
将字符串拆分为子字符串(如将句子拆分为各个单词)是一个常见的编程任务。Split() 方法使用分隔符(如空格字符)char 数组,并返回一个子字符串数组。您可以使用 foreach 访问此数组。
示例:
char[] delimit = new char[] { ' ' };
string s14 = "The cat sat on the mat.";
foreach (string substr in s14.Split(delimit))
{
System.Console.WriteLine(substr);
}
此代码将在单独的行上输出每个单词,如下所示:
The
cat
sat
on
the
mat.
下面的代码示例演示如何使用 System.String.Split 方法分析字符串。此方法返回一个字符串数组,其中每个元素是一个单词。作为输入,Split 采用一个字符数组指示哪些字符被用作分隔符。本示例中使用了空格、逗号、句点、冒号和制表符。一个含有这些分隔符的数组被传递给 Split,并使用结果字符串数组分别显示句子中的每个单词。
示例:
class TestStringSplit
{
static void Main()
{
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine("Original text: '{0}'", text);
string[] words = text.Split(delimiterChars);
System.Console.WriteLine("{0} words in text:", words.Length);
foreach (string s in words)
{
System.Console.WriteLine(s);
}
}
}
输出:
Original text: 'one two three:four,five six seven'
7 words in text:
one
two
three
four
five
six
seven
另外,还可通过正则表达式Regex.Split()的方法,通过字符串分隔字符串。
示例:
using System.Text.RegularExpressions; //需要引用正则表达式的命名空间
string str="aaajsbbbjsccc";
string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase); //正则表达式
// RegexOptions.IgnoreCase 表示忽略字母大小写
foreach (string i in sArray) Response.Write(i.ToString() + "<br>");
输出:
aaa
bbb
ccc