2015-07-20 89 views
0

我在替换多个文本时遇到了一些麻烦。 我知道替换文本是:C# - 替换多个文本

...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(); 
+1

如果你有这样一个字符串,这是一个字符串,你的替换列表是这个字符串,字符串,某些东西,是预期的产出? '“字符串是一个东西”或“”某物是某物“”? –

回答

6

你可以做的是做一些像这样:

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]); 

这样,你只需要一个集合中指定你的钥匙。这将允许你提取替换机制作为一种方法,例如可以接收字符串字典。

+0

它只将1替换为1,但是当我添加replaceWords.Add(“2”,“number2”);它不会取代和弄虚作假。 –

+0

@LewisOlive:您能否显示您使用的代码? – npinti

+0

我刚刚编辑它,并更新代码与你的代码,我也把输出。谢谢你和所有帮助我的其他人。 –

2

如果你有在具有替换的动态数量,这可以在任何时候改变任何计划,你想让它有点清洁,你总是可以做这样的事情:

// 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); 
} 
3

我将使用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是更好地在这里,因为它不会一个新字符串存储在每个内存替换操作。

2

如果我理解正确,您想要做多个替换而不需要再次编写替换。

我会建议编写一个方法,该方法需要一个字符串列表和一个输入字符串,然后遍历所有元素并调用input.replace(replacorList [i])。

据我所知,在.NET中的一种方法中没有多次替换的预制实现。

1

在特定情况下,当你想更换专门,你不应该忘记的正则表达式,用它你可以做这样的事情:

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"); 

这是一个品味的问题,但我觉得这是不是指定的一个字典找到替换双方式清洁,虽然你只能使用这个方法当你想插入一个前缀或类似于你的例子那样的东西。如果你有d或诸如此类的东西与bÇ更换一个 - 也就是说,你用不同的替代更换不同的项目 - ,你将不得不坚持Dictionary<String,String>方式。