开发者

Simple problem with replacing string value C#

i'm in a bit of a bind with a problem that's supposed to mediocre, but seemingly i can't implement the solution.

I have buttons, with a single char on each of them, 26 to be exact (english alphabet), When i click any of them, the loop iterates through the string for the text value on the b开发者_StackOverflowuttons and replaces it with quotation marks.

The code works, and it prints out the newAlphabet without the clicked character. But when i click another button, it returns the newAlphabet albeit with the previously removed character and removes the new clicked character.

The code is as follows

static string alphabet = "abcdefghijklmnopqrstuvwxyz";
static string newAlphabet = string.Empty;
Button tempBtn = (Button)sender;

for (int i = 0; i < alphabet.Length; i++)
{
  if (alphabet[i].ToString().Contains(tempBtn.Text))
  {
    newAlphabet = alphabet.Replace(tempBtn.Text, ""); 

    MessageBox.Show(newAlphabet);
  }
}

Sorry for grammar or spelling errors, english is not my first language.

Regards, HC


This line

 newAlphabet = alphabet.Replace(tempBtn.Text, ""); 

means you're always getting back to "abcdefghijklmnopqrstuvwxyz" and replacing that.

If you want to keep replacing letters, you need to replace on newAlphabet.


A simpler solution would be:

static string alphabet = "abcdefghijklmnopqrstuvwxyz";

private void button1_Click(object sender, EventArgs e)
{
  var tempBtn = (Button)sender;
  alphabet = alphabet.Replace(tempBtn.Text, "");
  MessageBox.Show(alphabet);
}

Note 1:
If the code you posted is in your button click event method then it would not compile. In C# you cannot declare variables static inside methods.

Note 2:
Strings are immutable so alphabet.Replace() returns a new string without affecting the original.


If the goal is to remove the clicked letter from the list:

static string newAlphabet = "abcdefghijklmnopqrstuvwxyz";
Button tempBtn = (Button)sender;

newAlphabet = newAlphabet.Replace(tempBtn.Text, ""); 

MessageBox.Show(newAlphabet);


Please note that strings are immutable in C#. "newAlphabet" is being continuously replaced by a modified "alphabet". It will never stick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜