Array.ToString() returning System.Char[] c#

前端 未结 4 1147
孤城傲影
孤城傲影 2020-12-11 21:09

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

相关标签:
4条回答
  • 2020-12-11 21:53

    Try this code:

    static string ConvertCharArr2Str(char[] chs)
    {
        var s = "";
        foreach (var c in chs)
        {
            s += c;
        }
        return s;
    }
    
    0 讨论(0)
  • 2020-12-11 21:58

    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.

    0 讨论(0)
  • 2020-12-11 22:00

    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.

    0 讨论(0)
  • 2020-12-11 22:00

    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));
    
    0 讨论(0)
提交回复
热议问题