3

I have this simple code for letter substitution. What I would like to add is, that if i.e., I replace letter A with letter T, all T letters are automatically replaced with A as well. So if I have a word "atatatat", the following code changes the word to "tttttttt", but it should change it to "tatatata". How can I fix this?

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(); } 

I tried with adding this line: newKey.Replace(letter2, letter1); But this changes word to "aaaaaaaa"

3 Answers 3

5

Just iterate through letters and change them one by one:

foreach(char c in key){ if(c==letter1){ newKey.Append(letter2); }else if(c==letter2){ newKey.Append(letter1); }else{ newKey.Append(c); } } 
Sign up to request clarification or add additional context in comments.

3 Comments

Tried it, but it returns the same word as the one provided at start. No idea how tho.
Try replacing String letter1 = this.textBox2.Text; with char letter1=this.textBox2.Text[0]; . Same for letter2.
This will do a replacement of the 2nd letter even if the 1st one isn't found.
1

You need to iterate over each letter, detect if you proceed with the change, and then do the second replacement only if the first one took place:

// 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(); 

Comments

0

try this one

var result = String.Join("", key.Select(c => c == letter2 ? letter1 : c == letter1 ? letter2 : c )); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.