1 回答

TA貢獻1811條經驗 獲得超6個贊
這是一個方法,它將接受輸入字符串,并通過查找“單詞”(任何連續的非空格)來構建一個新字符串,然后檢查該單詞是否在字典中,如果找到,則將其替換為相應的值。Replace這將解決“子詞”替換的問題(如果你有“hello hell”并且你想用“heaven”替換“hell”并且你不希望它給你“heaveno heaven”)。它還解決了交換問題。例如,如果您想將“yes no”中的“yes”替換為“no”,將“no”替換為“yes”,您不希望它首先將其變為“no no”,然后再變為“yes yes”。
public string ReplaceWords(string input, Dictionary<string, string> replacements)
{
var builder = new StringBuilder();
int wordStart = -1;
int wordLength = 0;
for(int i = 0; i < input.Length; i++)
{
// If the current character is white space check if we have a word to replace
if(char.IsWhiteSpace(input[i]))
{
// If wordStart is not -1 then we have hit the end of a word
if(wordStart >= 0)
{
// get the word and look it up in the dictionary
// if found use the replacement, if not keep the word.
var word = input.Substring(wordStart, wordLength);
if(replacements.TryGetValue(word, out var replace))
{
builder.Append(replace);
}
else
{
builder.Append(word);
}
}
// Make sure to reset the start and length
wordStart = -1;
wordLength = 0;
// append whatever whitespace was found.
builder.Append(input[i]);
}
// If this isn't whitespace we set wordStart if it isn't already set
// and just increment the length.
else
{
if(wordStart == -1) wordStart = i;
wordLength++;
}
}
// If wordStart is not -1 then we have a trailing word we need to check.
if(wordStart >= 0)
{
var word = input.Substring(wordStart, wordLength);
if(replacements.TryGetValue(word, out var replace))
{
builder.Append(replace);
}
else
{
builder.Append(word);
}
}
return builder.ToString();
}
- 1 回答
- 0 關注
- 281 瀏覽
添加回答
舉報