"Operator" == "cannot be applied to operands of type" char "and" string "

I searched this site for similar questions and the ones I found do not work for me. I apologize for asking if there is an answer somewhere, and I could not find it. Please let me know if I am doing something wrong by asking about it.

I am doing an executioner in C #. I made the program select a random string from the array, create an array of guessed letters (which it initially fills "_" until that word). Then he should get user input for the letter, see if this letter is in the word, and if so, add this letter to the array of guessed letters. I am stuck in this part:

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; } } } 

In " if (gameWord[x] == guessedLetter) " I get the error message indicated in the header.

gameWord is a string selected from an array of strings, and guessedLetter is a string entered by the user using Console.ReadLine(); .

+5
source share
3 answers

If guessedLetter is a string , you need to change one type to another. You can simply get the first guessedLetter character:

 if (gameWord[x] == guessedLetter[0]) 

or call ToString() on gameWord[x] , as another answer suggests.

However, you are about to face a much more serious problem. [] is a readonly operation ( MSDN ), because the lines are immutable, so your next line (assignment) will not be executed.

For this, you will need StringBuilder :

 StringBuilder sb = new StringBuilder(gameWord); sb[index] = guessedLetter[0]; gameWord = sb.ToString(); 

Confirm Replacing char with a given index in a string? for this code.

+4
source

You need to compare values โ€‹โ€‹of the same type. When receiving a character from gameWord, that is, gameWord [x] , this value is considered as char.

guessedLetter must also be of type char in order for the comparison to work.

I assume that guessedLetter has a string like here.

Here is an example:

 string gameWord = "Random"; char guessedLetter = char.Parse(Console.ReadLine()); for (int i=0; i < gameWord.length; i++) { if (gameWord[i] == guessedLetter) Console.WriteLine("Letter was found!"); } 
+2
source

gameWord [x] accesses the gameWord character, so it is a character, not a string. You can convert it to a string before comparing:

 if (gameWord[x].ToString() == guessedLetter) 
+1
source

Source: https://habr.com/ru/post/1211804/


All Articles