編輯:Uhg我剛剛意識到這個問題是2.0,但我會離開它,以防您有權訪問3.5。
只是另一個拿Linq的東西。現在我使用List <Char>而不是Char [],但這只是爲了讓它看起來更清潔。數組上沒有IndexOf方法,但List上有一個。我爲什麼需要這個?那麼從我的猜測來看,替換列表和被替換列表之間沒有直接關係。只是索引。
因此,考慮到這一點,你可以用Char []來做到這一點。但是當你看到IndexOf方法時,你必須在它之前添加一個.ToList()。
這樣的:someArray.ToList()的IndexOf
String text;
List<Char> patternsToReplace;
List<Char> patternsToUse;
patternsToReplace = new List<Char>();
patternsToReplace.Add('a');
patternsToReplace.Add('c');
patternsToUse = new List<Char>();
patternsToUse.Add('X');
patternsToUse.Add('Z');
text = "This is a thing to replace stuff with";
var allAsAndCs = text.ToCharArray()
.Select
(
currentItem => patternsToReplace.Contains(currentItem)
? patternsToUse[patternsToReplace.IndexOf(currentItem)]
: currentItem
)
.ToArray();
text = new String(allAsAndCs);
這只是將文本轉換爲一個字符陣列,通過每一個進行選擇。如果當前字符不在替換列表中,則按原樣發回字符。如果它位於替換列表中,則返回替換字符列表的相同索引中的字符。最後一件事是從字符數組中創建一個字符串。
using System;
using System.Collections.Generic;
using System.Linq;
可愛的輸出...你怎麼管理添加函數字符串雖然? – 2008-10-03 13:52:42