C#几种截取字符串的方法小结
1.根据单个分隔字符用split截取
string st="GT123_1";
string[] sArray=st.split("_");
即可得到sArray[0]="GT123",sArray[1]="1";
2.利用多个字符来分隔字符串
string str = "GTAZB_JiangjBen_123";
string[] sArray = str.Split(new char[2] { 'j', '_' });
foreach(string e in sArray)
{
Console.WriteLine(e);
}
得到sArray[0]="GTAZB",sArray[1]="Jiang",sArray[2]="Ben",sArray[3]="123";
3根据字符串或字符串组来截取字符串
string str = "GTAZB_JiangjBen_123";
string[] sArray = str.Split( new string[]{"Ji","jB"}, StringSplitOptions.RemoveEmptyEntries);
foreach(string e in sArray)
{
Console.WriteLine(e);
}
得到sArray[0]="GTAZB_",sArray[1]="ang",sArray[2]="en_123";
4提取字符串中的第i个字符开始的长度为j的字符串;
string str = "GTAZB_JiangjBen_123";
int start=3,length=8;
Console.WriteLine(str.Substring(start-1, length));
输出得到AZB_Jian。
string str = "GTAZB_JiangjBen_123";
string tSt;
int i=5;
tSt = str.Substring(str.Length - i);
Console.WriteLine(tSt);
输出n_123;
string str = "GTAZB_JiangjBen_123";
string tSt;
tSt = str.Replace("123","321");
Console.WriteLine(tSt);
输出GTAZB_JiangjBen_321
string str = "GTAZB_JiangjBen_123";
string tSt;
tSt = str.Replace("Jiangj","");
Console.WriteLine(tSt);
输出GTAZB_Ben_123
8删除指定位置(第i个)的指定长度(length)的字符串
代码如下:
string str = "GTAZB_JiangjBen_123";
int i=5,length=8;
str=str.remove(i,length);
console.writeline(str);
输出GTAZBen_123。