"运算符'=='不能应用于'char'和'string'类型的操作数"

use*_*505 5 c#

我在这个网站上搜索过类似的问题,而我发现的问题并不适用于我.我为询问答案是否在某个地方并且我无法找到而道歉.如果我这样做,请告诉我是否做错了.

我在C#做刽子手.我所做的就是让程序从一个数组中选取一个随机字符串,制作一个猜测字母的数组(它最初用"_"填充,只要这个单词是).然后它应该获得用户输入的字母,看看该字母是否在单词中,如果是,则将该字母添加到猜测的字母数组中.我被困在这个部分:

if (gameWord.Contains(guessedLetter)) 
{
    //for every character in gameWord
    for (int x = 0; x < gameWord.Length; x++)
    {
        //if the character at the 'x' position in gameWord is equal to the guessed letter
        if (gameWord[x] == guessedLetter)
        {
            //guessString at that x position is equal to the guessed letter
            guessString[x] = guessedLetter;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

在" if (gameWord[x] == guessedLetter)"我收到标题中显示的错误.

gameWord是从字符串数组中选择的字符串,而guessedLetter是用户输入的字符串Console.ReadLine();.

Bra*_*NET 5

如果guessedLetter是a string,则需要将一种类型更改为另一种类型.您可以轻松获得第一个字符guessedLetter:

if (gameWord[x] == guessedLetter[0])
Run Code Online (Sandbox Code Playgroud)

或致电ToString()gameWord[x]与其他答案建议.

但是,你要碰上很多更大的问题.[]是一个只读操作(MSDN),因为字符串是不可变的,所以你的下一行(赋值)将失败.

要做到这一点,你需要一个StringBuilder:

StringBuilder sb = new StringBuilder(gameWord);
sb[index] = guessedLetter[0];
gameWord = sb.ToString();
Run Code Online (Sandbox Code Playgroud)

感谢更换字符串中给定索引的char?对于那个代码.