2015-07-20 104 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>方式。