欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取字符串中指定字符间的字符串

程序员文章站 2022-07-14 19:27:04
...
 /// <summary>
    /// 获取字符串中指定字符间的字符串
    /// </summary>
    /// <param name="str">要截取的字符串</param>
    /// <param name="start">开始字符串</param>
    /// <param name="last">结束字符串</param>
    /// <param name="n">类型</param>
    /// <returns></returns>
    public string GetContent(string str, string start, string last, int n)
    {
        switch (n)
        {
            //左右都截取(都取前面)(包含关键字)
            case 1:
                str = str.Substring(str.IndexOf(start), str.Length - str.IndexOf(start));
                str = str.Substring(0, str.IndexOf(last) + last.Length);
                break;
            //左右都截取(都取前面)(去除关键字)
            case 2:
                str = str.Substring(str.IndexOf(start) + start.Length, str.Length - str.IndexOf(start) - start.Length);
                str = str.Substring(0, str.IndexOf(last));
                break;
            //左右都截取(都取后面)(包含关键字)
            case 3:
                str = str.Substring(str.LastIndexOf(start), str.Length - str.LastIndexOf(start));
                str = str.Substring(0, str.LastIndexOf(last) + last.Length);
                break;
            //左右都截取(都取后面)(去除关键字) 
            case 4:
                str = str.Substring(str.LastIndexOf(start) + start.Length, str.Length - str.LastIndexOf(start) - start.Length);
                str = str.Substring(0, str.LastIndexOf(last));
                break;
            //左右都截取(一前一后)(包含关键字)
            case 5:
                str = str.Substring(str.IndexOf(start), str.Length - str.IndexOf(start));
                str = str.Substring(0, str.LastIndexOf(last) + last.Length);
                break;
            //左右都截取(一前一后)(去除关键字) 
            case 6:
                str = str.Substring(str.IndexOf(start) + start.Length, str.Length - str.IndexOf(start) - start.Length);
                str = str.Substring(0, str.LastIndexOf(last));
                break;
            default:
                str = "";
                break;
        }
        return str;
    }

  

转载于:https://www.cnblogs.com/yhdkzy/archive/2012/01/11/2319555.html