我有这个简单的字母替换代码。我想补充的是,如果我用字母T替换字母A,所有T字母也会自动替换为A.因此,如果我有一个单词“atatatat”,下面的代码将单词更改为“tttttttt”,但它应该将其更改为“tatatata”。我该如何解决这个问题?
private void button3_Click(object sender, EventArgs e)
{
String key= this.textBox1.Text;
String letter1 = this.textBox2.Text;
String letter2 = this.textBox3.Text;
StringBuilder newKey = new StringBuilder();
newKey.AppendLine(key);
newKey.Replace(letter1, letter2);
this.textBox4.Text = noviKljuc.ToString();
}
我尝试添加这一行:newKey.Replace(letter2, letter1);
但这会改为“aaaaaaaa”
答案 0 :(得分:5)
只需迭代字母并逐一更改:
foreach(char c in key){
if(c==letter1){
newKey.Append(letter2);
}else if(c==letter2){
newKey.Append(letter1);
}else{
newKey.Append(c);
}
}
答案 1 :(得分:1)
您需要迭代每个字母,检测是否继续进行更改,然后仅在第一次更换时进行第二次更换:
// Check to see if we can find the 1st char to replace in the string
bool doReplace = key.Any(c => c == originalChar);
if (doReplace)
{
foreach (char c in key)
{
if (c == originalChar)
{
newKey.Append(alternateChar);
}
else if (c == alternateChar)
{
newKey.Append(originalChar);
}
else
{
newKey.Append(c);
}
}
}
else
{
newKey = key;
}
this.textBox4.Text = newKey.ToString();
答案 2 :(得分:0)
尝试这个
var result = String.Join("",
key.Select(c => c == letter2 ? letter1 : c == letter1 ? letter2 : c ));