Fork me on GitHub

【C#】字符串按条件替换关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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();
 
       }

 测试代码:

1
2
3
4
5
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 @   HelloLLLLL  阅读(216)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· 开发者新选择:用DeepSeek实现Cursor级智能编程的免费方案
· 【译】.NET 升级助手现在支持升级到集中式包管理
· 独立开发经验谈:如何通过 Docker 让潜在客户快速体验你的系统
· Tinyfox 发生重大改版
点击右上角即可分享
微信分享提示