字串擷取的方法
字串擷取的方法:
stringOf() lastIndexOf() Substring()
例項:
string str="123abc456";
int i=3;
1.取字串的前i個字元
str=str.Substring(0,i);// str=str.Remove(i,str.Length-i);
2.去除字串的前i個字元
str=str.Remove(0,i);//str=str.Substring(i);
3.從右邊開始取i個字元
str=str.Substring(str.Length-i);//
str=str.Remove(0,str.Length-i);
4.從右邊開始去掉i個字元
str=str.Substring(0,str.Length-i); // or str=str.Remove(str.Length-i,i);
5 判斷字串中是否有"abc" 有則去掉之
using System.Text.RegularExpressions;
string str = "123abc456";
string a="abc";
Regex r = new Regex(a);
Match m = r.Match(str);
if (m.Success)
{
//綠色部分與紫色部分取一種即可。
str=str.Replace(a,"");
Response.Write(str);
string str1,str2;
str1=str.Substring(0,m.Index);
str2=str.Substring(m.Index+a.Length,str.Length-a.Length-m.Index);
Response.Write(str1+str2);
}
6 如果字串中有"abc"則替換成"ABC"
str=str.Replace("abc","ABC");
lastIndexOf() 方法可返回一個指定的字串值最後出現的位置,在一個字串中的指定位置從後向前搜尋。
原文地址: