0

私はアプリを持っています。このアプリでは、単語内の一部の文字を別の文字に置き換える機能を使用できます

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";

currentCharacter を H AND L AND S に置き換えましたが、3 つすべてではなく H OR L OR S に置き換えたいだけです

したがって、HELLO を含む単語があり、O を newCharacter に置き換えたい場合、私の出力は HELLHLS O -> HLS ですが、O は -> H または L または S である必要があります。

4

3 に答える 3

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());
于 2013-03-06T09:11:30.543 に答える
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)]);

word now は EpqsdfSsqfdEomHmeS または SpqsdfSsqfdHomHmeE または ...

于 2013-03-06T09:12:17.710 に答える
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;
}
于 2013-03-06T09:14:21.357 に答える