Ólafur Aron
Ólafur Aron

Reputation: 352

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 buttons 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

Upvotes: 1

Views: 208

Answers (4)

Sani Huttunen
Sani Huttunen

Reputation: 24395

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.

Upvotes: 1

feathj
feathj

Reputation: 3069

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

Upvotes: 0

Jonathan M
Jonathan M

Reputation: 17451

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

Upvotes: 0

Peter K.
Peter K.

Reputation: 8108

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.

Upvotes: 2

Related Questions