Fork me on GitHub

【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是你的特殊条件,当满足这个条件,才会替换关键字。

posted @ 2021-06-21 16:48  HelloLLLLL  阅读(209)  评论(0编辑  收藏  举报