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

Asked

Viewed 1,491 times

3

I’m doing a hangman’s game, let’s suppose I type the name "john" into a box of text, then I press a button and I want the "text 2" box to have "_ _ _", so I want the same number of underscore that the number of letters.

3 answers

5


There is a ready-made builder to do this then 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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

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

3

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

Exemplary:

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

Or else 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 on the screen the example, there are other ways to do, depends on how you will display this text.

2

In addition to what has been answered previously 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 do similar to gallows just put a space after the Undescore character:

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

O resultado é: _ _ _ _ _ _ _ _  _ _ _ _ _

Browser other questions tagged

You are not signed in. Login or sign up in order to post.