///<summary> ///取出文本中間內容 ///<summary> ///<param name="left">左邊文本</param> ///<param name="right">右邊文本</param> ///<param name="text">全文本</param> ///<return>完事返回成功文本|沒有找到返回空</return> public static string TextGainCenter(string left, string right, string text) { //判斷是否為null或者是empty if (string.IsNullOrEmpty(left)) return ""; if (string.IsNullOrEmpty(right)) return ""; if (string.IsNullOrEmpty(text)) return ""; //判斷是否為null或者是empty int Lindex = text.IndexOf(left); //搜索left的位置 if (Lindex == -1){ //判斷是否找到left return ""; } Lindex = Lindex + left.Length; //取出left右邊文本起始位置 int Rindex = text.IndexOf(right, Lindex);//從left的右邊開始尋找right if (Rindex == -1){//判斷是否找到right return ""; } return text.Substring(Lindex, Rindex - Lindex);//返回查找到的文本 }
例子:
left(string):指定的左邊文本 例:前
right(string):指定的右邊文本 例:左
text(string):欲查找的全部文本 例:前后左右
TextGainCenter("前","左","前后左右");
結果:"右"
解釋:
用到的方法
IndexOf(left)
這個是用來獲取left也就是"前"在text(前后左右)中的位置 用Lindex表示
Lindex = Lindex + left.length
獲取的位置是在left開始的位置 例: 獲取的位置 (|前后左右) “|”為輸入時的光標
用獲取的位置加上left的長度就是left右邊第一個字符的起始位置 例: 獲取的位置 (前|后左右) “|”為輸入時的光標
IndexOf(right,Lindex)
這個用來獲取在left右邊的right在text中的位置 用Rindex表示
{
因為這是取的left和right中間的內容,如果left左邊有字符與right相同的話,Rindex會返回left左邊那個字符的位置
}
Substring(開始截取的位置,截取的字符串長度)
text.Substring(Lindex,Rindex-Lindex)
Rindex - Lindex = left與right中間字符串的長度
所以用這個方法返回的結果為:后