[英]C# - Replacing multiple text
我在替换多个文本时遇到了一些麻烦。 我知道要替换的文字是:
...Text.Replace("text", "replaced");
我没有关于如何更改多个文本的线索,我尝试了下面的代码,但是没有用,我在网络上进行了一些搜索以寻求帮助,但是我没有发现任何可以帮助我的东西,所以我提出了这个问题。 这是我到目前为止所拥有的:
string[] List =
{
"1", "number1",
"2", "number2",
"3", "number3",
"4", "number4",
};
writer.WriteLine(read.
Replace(List[0], List[1]).
Replace(List[2], List[3]).
Replace(List[4], List[5])
);
writer.Close();
您可能会做的是这样的事情:
Dictionary<string, string> replaceWords = new Dictionary<string, string>();
replaceWords.Add("1", "number1");
...
StringBuilder sb = new StringBuilder(myString);
foreach(string key in replaceWords.Keys)
sb.Replace(key, replaceWords[key]);
这样,您只需要在集合中指定密钥即可。 这样,您就可以将替换机制提取为一种方法,例如可以使用字符串字典。
我将使用Linq来解决它:
StringBuilder read = new StringBuilder("1, 2, 3");
Dictionary<string, string> replaceWords = new Dictionary<string, string>();
replaceWords.Add("1", "number1");
replaceWords.Add("2", "number2");
replaceWords.Add("3", "number3");
replaceWords.ForEach(x => read.Replace(x.Key, x.Value));
注意:此处的StringBuilder
更好,因为它不会在每次替换操作时将新字符串存储在内存中。
如果您有任何计划来动态替换,并且随时可以更改,并且想要使其更整洁,则可以始终执行以下操作:
// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<find>", client.find);
replacements.Add("<replace>", event.replace.ToString());
// Replace
string s = "Dear <find>, your booking is confirmed for the <replace>";
foreach (var replacement in replacements)
{
s = s.Replace(replacement.Key, replacement.Value);
}
如果我理解正确,则您想进行多次替换,而无需再次写替换。
我建议编写一个方法,该方法接受一个字符串列表和一个输入字符串,然后遍历所有元素并调用input.replace(replacorList [i])。
据我所知,.NET中还没有一种针对多种替换的预制实现。
在您的特定情况下,当您要专门替换数字时 ,您不应忘记正则表达式,使用正则表达式可以执行以下操作:
Regex rgx = new Regex("\\d+");
String str = "Abc 1 xyz 120";
MatchCollection matches = rgx.Matches(str);
// Decreasing iteration makes sure that indices of matches we haven't
// yet examined won't change
for (Int32 i = matches.Count - 1; i >= 0; --i)
str = str.Insert(matches[i].Index, "number ");
Console.WriteLine(str);
这样,您可以替换任何数字(尽管这可能很奇怪),但是调整正则表达式以使其符合您的需求应该可以解决您的问题。 您还可以指定正则表达式来匹配某些数字,如下所示:
Regex rgx = new Regex("1|2|3|178");
这是一个问题,但我认为这比指定查找-替换对字典更干净,尽管您只能在想要插入前缀或类似示例中的内容时使用此方法。 如果必须将a替换为 b ,将c替换为 d或其他(即用不同的替换项替换不同的项目),则必须坚持使用Dictionary<String,String>
方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.