C# 截取两个指定字符串中间的字符串列表
/// <summary> /// 截取两个指定字符串中间的字符串列表(开始和结束两个字符串不能相同!) /// </summary> /// <param name="content"></param> /// <param name="startStr"></param> /// <param name="endStr"></param> /// <returns></returns> public static List<string> GetAllSubstring(string content, string startStr, string endStr) { List<string> resultList = new List<string>(); int len = content.Length; int startLen = startStr.Length; int endLen = endStr.Length; for (var i = 0; i < len; i++) { string a = startStr.Substring(0, 1); if (content[i].ToString() == a) { int startIndex = (i + startLen - 1); if (startIndex < len) { a = content.Substring(i, startLen); if (a.Equals(startStr)) { // 循环找出结尾匹配 for (int endIndex = startIndex; endIndex < len; endIndex++) { var str = ""; for (int j = 0; j < endLen; j++) { str += content[endIndex].ToString(); } if (str == endStr&&endStr!=startStr) { // 得到长度 int splLen = endIndex - startIndex; string result = content.Substring(startIndex + 1, splLen - 1); resultList.Add(result); break; } } } } } } return resultList; }
例如
var content = "{{first.DATA}}\n\n职位名称:{{job.DATA}}\n公司名称:{{company.DATA}}\n投递时间:{{time.DATA}}\n{{remark.DATA}}"; var start = "{{"; var end = "}}"; var list =CommonHelper.GetAllSubstring(content, start, end);