-3

I am writing a windows form app in C#. I have a label with a random word, e.g. "computer". User has to guess what is this word by guessing letter by letter. But word "computer" must be replaced with as many "x" as there is letters in a word, so in this example user should see "xxxxxxxx".

I tried to replace it with regex like this:

private void Form1_Load(object sender, EventArgs e)
{
    word.Text = Regex.Replace(word.Text, @"^[a-zA-Z]+$", "x");
}

But it only replace with single "x".

I also tried with for loop, but the result is the same:

private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 0; i <= word.Text.Length; i++)
    {
        word.Text = Regex.Replace(word.Text, @"^[a-zA-Z]+$", "x");
    }
}
  • you need replace computer word to xxxx from text? It is "my text computer".Replace("computer", "x-x-x") – daremachine Jun 24 '21 at 12:32
  • look at your code: you are replacing _any amount of letters_ with _one_ x. what you should do is replace _one_ of any letter with _one_ x. try removing the `+` (which says: one or more of the previous item) – Franz Gleichmann Jun 24 '21 at 12:32
  • @FranzGleichmann while I remove + it doesn't replace any letter – keyboardNoob Jun 24 '21 at 12:35
  • You can simply use PadRight(). ie: var xxx = "".PadRight(word.Text.Length, 'x'); Or, it looks like you are using winforms, you could use a password textbox. – Cetin Basoz Jun 24 '21 at 12:35
  • why not use built in `passwordchar` of textbox? – Lei Yang Jun 24 '21 at 12:37

3 Answers3

2

You can create a new string of "x" repeated the number of characters in your word. No need for regexes.

word.Text = new string('x', word.Text.Length);
Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
  • A minor correction to this answer, `new string()` expects a `char` therefore, it would be single quote around as in `"x" => 'x'` – Shuvo Amin May 05 '22 at 17:25
1

Approach without RegEx

string wordText = "computer";
wordText = string.Concat(wordText.Select(x => char.IsLetter(x) ? 'x' : x));

if you want to stay with RegEx, replace @"^[a-zA-Z]+$" with "[a-zA-Z]" to match every single character

fubo
  • 44,811
  • 17
  • 103
  • 137
0

Try this:

word.Text=String.Join("",word.Text.Select(s=>s='x').ToArray());
Tabris
  • 37
  • 1
  • 5