[英]How to replace characters in a string?
我想替換文件中字符串內容中的字符。 下面的字典顯示密鑰為不需要的字符,我需要替換為字典中的值。
Dictionary<string, string> unwantedCharacters = new Dictionary<string, string>();
unwantedCharacters["É"] = "@";
unwantedCharacters["Ä"] = "[";
unwantedCharacters["Ö"] = "\\";
unwantedCharacters["Å"] = "]";
unwantedCharacters["Ü"] = "^";
unwantedCharacters["é"] = "`";
unwantedCharacters["ä"] = "{";
unwantedCharacters["ö"] = "|";
unwantedCharacters["å"] = "}";
unwantedCharacters["ü"] = "~";
這是我當前使用的代碼,感覺它占用了太多的執行時間。
for (int index = 0; index < fileContents.Length; index++)
{
foreach (KeyValuePair<string, string> item in unwantedCharacters)
{
if (fileContents.IndexOf(item.Key) > -1)
{
fileContents = fileContents.Replace(item.Key, item.Value); // Replacing straight characters
}
}
}
即,分為兩個層次。任何其他方式實現此目標。任何幫助將不勝感激
由於您沒有修改字符串的長度,因此,如果將unwantedCharacters
的Dictionary<char, char>
而不是<string, string>
,則可以執行以下操作:
var charArray = fileContents.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char replacement;
if (unwantedCharacters.TryGetValue(charArray[i], out replacement))
charArray[i] = replacement;
}
fileContents = new string(charArray);
相對於輸入字符串的長度,性能為O(n)
。
看這個答案: 答案
但是在此代碼中放置您的角色:
IDictionary<string,string> map = new Dictionary<string,string>()
{
{"É", = "@"},
{"Ä", = "["},
{"Ö", = "\\"},
...
};
似乎fileContents是一個字符串值。 您可以簡單地在字符串上調用replace。
foreach (KeyValuePair<string, string> item in unwantedCharacters)
{
fileContents = fileContents.Replace(item.Key, item.Value);
}
為了替換字符串中的許多字符,請考慮使用StringBuilder Class 。 替換字符串中的一個字符會導致創建全新的字符串,因此效率很低。 請嘗試以下方法:
var sb = new StringBuilder(fileContents.Length);
foreach (var c in fileContents)
sb.Append(unwantedCharacters.ContainsKey(c) ? unwantedCharacters[c] : c);
fileContents = sb.ToString();
我在這里假設您的字典包含字符( Dictionary<char, char>
)。 在這種情況下,只需發表評論即可,我將編輯解決方案。
我還假設, fileContents
是一個字符串。
您也可以使用LINQ代替StringBuilder :
var fileContentsEnumerable = from c in fileContents
select unwantedCharacters.ContainsKey(c) ? unwantedCharacters[c] : c;
fileContents = new string(fileContentsEnumerable.ToArray());
您要構建一個過濾器 。 您處理文件的內容,並在處理文件時進行替換。
像這樣:
using(StreamReader reader = new StreamReader("filename"))
using (StreamWriter writer = new StreamWriter("outfile"))
{
char currChar = 0;
while ((currChar = reader.Read()) >= 0)
{
char outChar = unwantedCharacters.ContainsKey(currChar)
? unwantedCharacters[currChar]
: (char) currChar;
writer.Write(outChar);
}
}
如果數據在內存中,則可以使用內存流,或者通過fileContents
循環是一個字符串或char數組。
該解決方案是O(n),其中n是文件的長度,這要歸功於字典(請注意,您可以使用簡單的稀疏數組而不是字典,這樣可以提高速度)。
不要像其他建議那樣遍歷字典,因為每次替換都是O(n),所以最終總時間為O(n * d),d為字典大小,因為您必須多次瀏覽文件。
刪除foreach
並用從0到item.Count
的for
循環item.Count
。 希望本文對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.