zoukankan      html  css  js  c++  java
  • c#如何取出指定的中间文本

     ///<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中间字符串的长度

    所以用这个方法返回的结果为:后

  • 相关阅读:
    HDU 1075 What Are You Talking About(字典树)
    HDU 1075 What Are You Talking About (stl之map映射)
    HDU 1247 Hat’s Words(字典树活用)
    字典树HihoCoder
    HDU 1277全文检索(字典树)
    HDU 3294 Girls' research(manachar模板题)
    HDU 3294 Girls' research(manachar模板题)
    HDU 4763 Theme Section(KMP灵活应用)
    Ordering Tasks UVA
    Abbott's Revenge UVA
  • 原文地址:https://www.cnblogs.com/codedisco/p/12915377.html
Copyright © 2011-2022 走看看