4

Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.

code:

class Program
{
    static void Main(string[] args)
    {
        string PlayerOneWord;
        string PlayerTwoGuess;
        int lives = 5;

        Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
        PlayerOneWord = Console.ReadLine().ToLower();

        var stars = new char[PlayerOneWord.Length];
        for (int i = 0; i < stars.Length ; i++)
        {
                stars[i] = '*';
        }

        string StarString = stars.ToString();

        Console.Write("Word to Guess: {0}" , StarString);

        Console.ReadLine();
    }
}

output:

Output

The output should say Word to guess: Hello.

Please will someone explain why this is happening as its not the first time I have run into this problem.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
Needham
  • 457
  • 1
  • 6
  • 15

4 Answers4

8

Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].

To convert a char[] to string you can use:

string s = new string(charArray);

But for your concrete problem there is an even simpler solution:

string stars = new string('*', PlayerOneWord.Length);

The constructor public String(char c, int count) repeats c count times.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
2

The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN

Returns a string that represents the current object.

In order you get a string from the characters in this array, you could use this:

 Console.Write("Word to Guess: {0}" , new String(stars));
Christos
  • 53,228
  • 8
  • 76
  • 108
1

The correct way to do this would be:

string StarString = new string(stars);

ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.

Oliver Ulm
  • 531
  • 3
  • 8
0

Try this code:

static string ConvertCharArr2Str(char[] chs)
{
    var s = "";
    foreach (var c in chs)
    {
        s += c;
    }
    return s;
}