0

Getting error saying: operator '==' cannot be applied to type string or char

string word = Console.ReadLine(); int wordlength; bool pass; for(int i = 0; pass == false; ++i){ if (word[i] == " "){ // nothing happens } else if (word[i] == null){ pass = true; } else{ wordlength += 1; } }

11th Jan 2017, 2:43 PM
Henry Smallio
Henry Smallio - avatar
11 odpowiedzi
+ 4
just replace " " by ' ' when you compare the word[i] to " " you try to compare a char to a string
12th Jan 2017, 6:01 PM
vincent PHILIPPE
vincent PHILIPPE - avatar
+ 2
use 'single quotes' or " double quotes " when writing any string at any programming or scripting language..thats an important point for any software developer example a = "hello world"; b = 2345;
12th Jan 2017, 9:15 PM
ARNAB BISWAS
ARNAB BISWAS - avatar
+ 1
I have used .equals method in java for string n char search any such method in c#.
11th Jan 2017, 3:34 PM
Divesh Agarwal
Divesh Agarwal - avatar
+ 1
@Vincent philippe you absolute life saver. thanks a lot my man. if anybody wants the working code it looks like this: string word = Console.ReadLine(); int wordlength = 0; for(int i = 0; i< word.Length ++i){ if (word[i] == ' '){ // nothing happens } else{ wordlength += 1; } }
12th Jan 2017, 10:16 PM
Henry Smallio
Henry Smallio - avatar
+ 1
@Vincent philippe what do you mean? I have shortened it again because the else was not needed and it now looks like this: string word = Console.ReadLine(); int wordlength = 0; for(int i = 0; i< word.Length ; ++i){ if (word[i] != ' '){ ++wordlength; } } it still works perfectly and it's the shortest I can possibly make it myself. I have used this in a bit of code I have made if you want to check it out.
13th Jan 2017, 12:38 AM
Henry Smallio
Henry Smallio - avatar
0
That didn't work. it's saying "string.this[int] is read only and can't be assigned' so that didn't work. it also says that type char is not a nullable type so I may need to change that also. this code may be completely wrong. I apologise in advance. I've only started learning c# 3 days ago
11th Jan 2017, 3:00 PM
Henry Smallio
Henry Smallio - avatar
0
Perhaps pass could be initialized to being false. I do not know how C# handles variables that are not initialized.
12th Jan 2017, 4:36 PM
Dwane Christensen
Dwane Christensen - avatar
0
Never delete a code, always search the mistake, else you never gonna learn and never progresse
12th Jan 2017, 10:23 PM
vincent PHILIPPE
vincent PHILIPPE - avatar
0
first you have do remove the first if statement wich is useless and alter the else if to if
12th Jan 2017, 10:26 PM
vincent PHILIPPE
vincent PHILIPPE - avatar
0
this is an update of your code : string word = Console.ReadLine(); int wordlength = 0; foreach(char c in word){ if (c != ' '){ wordlength += 1; } } Console.WriteLine(wordlength); When you don't know how many time you have to loop, you should use foreach not for
13th Jan 2017, 6:04 AM
vincent PHILIPPE
vincent PHILIPPE - avatar