我有一个看起来像这样的字符串
Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye
它有16'〜'将它分成17个“部分”。在第5节中,我需要插入Say_Opt5
。
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5~Say_Opt6~~~Say_Opt9~~Say_GoodBye
所以我需要能够获取一个字符串和一个位置,并将字符串isert到指定的位置。我尝试使用正则表达式,但我不完全确定匹配是如何工作的。
string baseString = "Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye";
var newString = new Regex("~").Replace(baseString, "Say_Opt5", 7);
此外,可能已经存在选项5,因此我需要使用新选项5替换旧选项5.例如替换
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5~Say_Opt6~~~Say_Opt9~~Say_GoodBye
与
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5_Custom~Say_Opt6~~~Say_Opt9~~Say_GoodBye
答案 0 :(得分:2)
var s1 = "there~is~a~~cat";
var s2 = "super";
var words = s1.Split('~').ToList();
//words.Insert(3, s2); // this will insert new token
words[3] = s2; // this will replace word at specific index
var res = string.Join("~", words.ToArray());
在此之后你的猫将成为一个超级英雄,它将成为超级猫:)
答案 1 :(得分:0)
如果您使用的是C#,可以使用:
string s = "Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye";
MessageBox.Show(s);
string[] parts = s.Split('~');
parts[YourIntegerIndex] = "YouNewString";
s = string.Join("~", parts);
MessageBox.Show(s);