【C#】字串按條件替換關鍵字
阿新 • • 發佈:2021-06-21
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是你的特殊條件,當滿足這個條件,才會替換關鍵字。