zoukankan      html  css  js  c++  java
  • 【C#】字符串按条件替换关键字

     private string MyReplace(string json, string keyWord, string newWord, Func<string, string, bool> func)
            {
                StringBuilder sb = new StringBuilder();
                int preIndex = 0;
                int oldLen = keyWord.Length;
                int lastIndex = json.LastIndexOf(keyWord);
               
                while (true)
                {
                    int idx = json.IndexOf(keyWord, preIndex);
    
                    if (idx < 0)
                    {
                        return json;
                    }
                   
                        var temp = json.Substring(preIndex, idx - preIndex);
                        sb.Append(temp);
                        var temp1 = string.Empty;
                        var temp2 = string.Empty;
                        
    
                        if (idx - 1 < 0)
                        {
                            temp1 = "";
                        }
                        else {
    
                            temp1 = json.Substring(idx - 1, 1);
                        }
                        if (idx + oldLen >= json.Length)
                        {
                            temp2 = "";
                        }
                        else
                        {
                            temp2= json.Substring(idx + oldLen, 1);
                        }
                        if (func(temp1,temp2))
                        {
                           
                            sb.Append(newWord);
                        }
                        else
                        {
                            sb.Append(keyWord);
                        }
                    
                   
                     preIndex = idx + oldLen;
                      
                    if (preIndex > lastIndex)
                    {
                        break;
                    }
    
    
                }
                if (preIndex < json.Length)
                {
                    sb.Append(json.Substring(preIndex));
                }
    
    
                return sb.ToString();
    
            }
    

     测试代码:

     string json = ""abc"{"abc":"13","jeabcje":23,"jabc":234,"abcJ":567,"a13":323,"ggg":"end"}"abc":12abc3";
               
                string keyWord = "abc";
                string newWord = "Keys";
                string str = MyReplace(json, keyWord, newWord, (a, b) => { return a == """ && b == """; });
    

    主要功能是把json里 属性替换掉,比如"abc"属性 替换成“Keys”,而不会把“jeabcje”这种包含abc的属性也替换为Key。

    func是你的特殊条件,当满足这个条件,才会替换关键字。

  • 相关阅读:
    关系数据理论
    JavaScript语言——对象
    网络编程基础入门级
    数据库加快查询速度索引
    C/C++随机函数的生成(转载)
    sql连接查询
    深入浅出HTTP请求
    17搜索如何抓全网页
    搜索引擎之百度一下
    搜索引擎之中搜
  • 原文地址:https://www.cnblogs.com/HelloQLQ/p/14914405.html
Copyright © 2011-2022 走看看