C#字串操作 取文字左邊 取文字右邊 取文字中間 取文字中間到List集合 指定文字倒序

RootSuper發表於2012-08-04
        /// <summary>
        /// 取文字左邊內容
        /// </summary>
        /// <param name="str">文字</param>
        /// <param name="s">識別符號</param>
        /// <returns>左邊內容</returns>
        public static string GetLeft(string str, string s)
        {
            string temp = str.Substring(0, str.IndexOf(s));
            return temp;
        }


        /// <summary>
        /// 取文字右邊內容
        /// </summary>
        /// <param name="str">文字</param>
        /// <param name="s">識別符號</param>
        /// <returns>右邊內容</returns>
        public static string GetRight(string str, string s)
        {
            string temp = str.Substring(str.IndexOf(s), str.Length-str.Substring(0, str.IndexOf(s)).Length);
            return temp;
        }

        /// <summary>
        /// 取文字中間內容
        /// </summary>
        /// <param name="str">原文字</param>
        /// <param name="leftstr">左邊文字</param>
        /// <param name="rightstr">右邊文字</param>
        /// <returns>返回中間文字內容</returns>
        public static string Between(string str, string leftstr, string rightstr)
        {
            int i = str.IndexOf(leftstr) + leftstr.Length;
            string temp = str.Substring(i, str.IndexOf(rightstr, i) - i);
            return temp;
        }


        /// <summary>
        /// 取文字中間到List集合
        /// </summary>
        /// <param name="str">文字字串</param>
        /// <param name="leftstr">左邊文字</param>
        /// <param name="rightstr">右邊文字</param>
        /// <returns>List集合</returns>
        public List<string> BetweenArr(string str, string leftstr, string rightstr)
        {
            List<string> list = new List<string>();
            int leftIndex = str.IndexOf(leftstr);//左文字起始位置
            int leftlength = leftstr.Length;//左文字長度
            int rightIndex = 0;
            string temp = "";
            while (leftIndex != -1)
            {
                rightIndex = str.IndexOf(rightstr, leftIndex + leftlength);
                if (rightIndex == -1)
                {
                    break;
                }
                temp = str.Substring(leftIndex + leftlength, rightIndex - leftIndex - leftlength);
                list.Add(temp);
                leftIndex = str.IndexOf(leftstr, rightIndex + 1);
            }
            return list;
        }


        /// <summary>
        /// 指定文字倒序
        /// </summary>
        /// <param name="str">文字</param>
        /// <returns>倒序文字</returns>
        public static string StrReverse(string str)
        {
            char[] chars = str.ToCharArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < chars.Length; i++)
            {
                sb.Append(chars[chars.Length - 1 - i]);
            }
            return sb.ToString();
        }

相關文章