导航

C# 分割字符串

Posted on 2019-09-13 10:08  ZeroSymbol  阅读(46815)  评论(0编辑  收藏  举报
using System.Text.RegularExpressions;//引用命名空间

 

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