C# 分割字符串几种方式小结

1、普通分割字符串方式

string str = "a,b,c";
string[] arr = str.Split(',');

foreach (string s in arr)
{
    Console.WriteLine(s);
}

->输出结果:

a
b
c

2、利用字符串进行分割字符串方式

string str = "a字体b字体c字体d字体e";
string strTemp = "字体";
string[] arr = Regex.Split(str, strTemp, RegexOptions.IgnoreCase);

foreach (string s in arr)
{
    Console.WriteLine(s);
}

->输出结果:

a
b
c
d
e

3、多个字符分割字符串方式

string str = "a,b,c@d$e";
char[] charTemp = {',', '@', '$'};
string[] arr = str.Split(charTemp);

foreach (string s in arr)
{
    Console.WriteLine(s);
}

string str = "a,b,c@d$e";
string[] arr = str.Split(new char[] { ',', '@', '$' });

foreach (string s in arr)
{
    Console.WriteLine(s);
}

->输出结果:

a
b
c
d
e

4、分割字符串且去除空字符数组方式

string str = "a,,,b,c,d,e";
string[] arr = str.Split(',');

foreach (string s in arr)
{
    Console.WriteLine(s);
}

->输出结果:

a


b
c
d
e

string str = "a,,,b,c,d,e";
string[] arr = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in arr)
{
    Console.WriteLine(s);
}

->输出结果:

a
b
c
d
e

5、分割字符串且不区用作分割字符串的字符的大小写方式

string str = "bacAdae";
string[] arr = Regex.Split(str, "a", RegexOptions.IgnoreCase);
foreach (string s in arr)
{
    Console.WriteLine(s);
}

->输出结果:

b
c
d
e

猜你喜欢

转载自www.cnblogs.com/zerosymbol/p/11516136.html
今日推荐