使用多个字符替换其他字符

时间:2013-03-06 08:52:10

标签: c#

我有一个应用程序,在这个应用程序中,可以使用函数将一个单词中的某些字符替换为另一个字符

var newCharacter = "H";

if (/*something happens here and than the currentCharacter will be replaced*/)
{
    // Replace the currentCharacter in the word with a random newCharacter.
    wordString = wordString.Replace(currentCharacter, newCharacter);
}

现在所有的字符都将被上面的代码替换为“H”。但我想要更多的字母,例如H,E,A,S

这样做的最佳方式是什么?

当我这样做时:

var newCharacter = "H" + "L" + "S";

它用H AND L AND S替换了currentCharacter,但我只想用H OR L或S替换所有三个

所以,如果你对HELLO说了一句话,并且你想用newCharacter替换O,我的输出现在是HELLHLS O - > HLS 但是O需要 - > H或L或S

3 个答案:

答案 0 :(得分:0)

以下是使用LINQ的方法。您可以在数组中添加要删除的字符 excpChar

char[] excpChar= new[] { 'O','N' };
string word = "LONDON";

var result = excpChar.Select(ch => word = word.Replace(ch.ToString(), ""));
Console.WriteLine(result.Last());

答案 1 :(得分:0)

Replace函数会立即替换所有出现的事件,这不是我们想要的。让我们做一个ReplaceFirst函数,只替换第一次出现(一个可以用这个扩展方法):

static string ReplaceFirst(string word, char find, char replacement)
{
    int location = word.IndexOf(find);
    if (location > -1)
        return word.Substring(0, location) + replacement + word.Substring(location + 1);
    else
        return word;
}

然后我们可以使用随机生成器通过连续调用ReplaceFirst来用不同的字母替换目标字母:

string word = "TpqsdfTsqfdTomTmeT";
char find = 'T';
char[] replacements = { 'H', 'E', 'A', 'S' };
Random random = new Random();

while (word.Contains(find))
    word = ReplaceFirst(word, find, replacements[random.Next(replacements.Length)]);

现在可能是EpqsdfSsqfdEomHmeS或SpqsdfSsqfdHomHmeE或......

答案 2 :(得分:0)

你可以这样做:

string test = "abcde";
var result = ChangeFor(test, new char[] {'b', 'c'}, 'z');
// result = "azzde"

使用ChangeFor:

private string ChangeFor(string input, IEnumerable<char> before, char after)
{
    string result = input;
    foreach (char c in before)
    {
        result = result.Replace(c, after);
    }
    return result;
}
相关问题