'c# replace string with many "x" [duplicate]
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");
}
}
Solution 1:[1]
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);
Solution 2:[2]
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
Solution 3:[3]
Try this:
word.Text=String.Join("",word.Text.Select(s=>s='x').ToArray());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | fubo |
Solution 3 | Tabris |