System.StringHelper.Substring C# (CSharp) Method

Substring() public static method

从字符串中检索子字符串,在指定头部字符串之后,指定尾部字符串之前
常用于截取xml某一个元素等操作
public static Substring ( String str, String after, String before = null, Int32 startIndex, Array positions = null ) : String
str String 目标字符串
after String 头部字符串,在它之后
before String 尾部字符串,在它之前
startIndex Int32 搜索的开始位置
positions Array 位置数组,两个元素分别记录头尾位置
return String
        public static String Substring(this String str, String after, String before = null, Int32 startIndex = 0, Int32[] positions = null)
        {
            if (String.IsNullOrEmpty(str)) return str;
            if (String.IsNullOrEmpty(after) && String.IsNullOrEmpty(before)) return str;

            /*
             * 1,只有start,从该字符串之后部分
             * 2,只有end,从开头到该字符串之前
             * 3,同时start和end,取中间部分
             */

            var p = -1;
            if (!String.IsNullOrEmpty(after))
            {
                p = str.IndexOf(after, startIndex);
                if (p < 0) return null;
                p += after.Length;

                // 记录位置
                if (positions != null && positions.Length > 0) positions[0] = p;
            }

            if (String.IsNullOrEmpty(before)) return str.Substring(p);

            var f = str.IndexOf(before, p >= 0 ? p : startIndex);
            if (f < 0) return null;

            // 记录位置
            if (positions != null && positions.Length > 1) positions[1] = f;

            if (p >= 0)
                return str.Substring(p, f - p);
            else
                return str.Substring(0, f);
        }