How to replace the number of letters of a word with a character?

4

I'm doing a hangman game, let's suppose I type the name "john" in a text box, shortly after I press a button and I want it in the "text 2" box to appear " _ _ _ _ ", then I want the same number of underlines to appear as the number of letters.

    
asked by anonymous 03.06.2017 / 20:40

3 answers

5

There is a ready builder to do this so it is very simple.

using System;

public class Program {
    public static void Main() {
        var texto = "carambola";
        var adivinha = new String('_', texto.Length);
        Console.WriteLine(adivinha);
    }
}

See running on .NET Fiddle . And at Coding Ground . Also put it on GitHub for future reference .

If you make a loop by adding strings is slower and does damage to the garbage collector . It may not be important to do it in a very simple game, but if you learn wrong something simple will reproduce something that matters more. At least you could use StringBuilder in this case , but it would also be an exaggeration.

    
03.06.2017 / 21:43
3

You can use the string.Length to know the size of the word you have. Then you can Iterar over that size by typing "_"

Exemplary:

for(int i=0; i< string.Legth; i++)
{
  // aqui você pode criar um string igual ao seu exemplo
  novaString += "_";
}

Or with foreach

foreach(Char caracter in SuaString)
{
  // aqui você pode criar um string igual ao seu exemplo
  novaString += "_";
}

Then you can use your novaString to show the example screen, there are other ways to do it depends on how you will show this text.

    
03.06.2017 / 21:03
2

In addition to what has been previously answered you can use regular expression 'Regex' with the replace function, replacing the characters.

string txt = "Primeiro Teste";
string forca=   Regex.Replace(txt, "[\w]", "_");

O resultado é: ________ _____

If you prefer to make similar to the gallows just place a space after the Undescore character:

string txt = "Primeiro Teste";
string teste2 = Regex.Replace(txt, "[\w]", "_ ");

O resultado é: _ _ _ _ _ _ _ _  _ _ _ _ _
    
08.06.2017 / 15:51