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; } }
11 odpowiedzi
+ 4
just replace " " by ' '
when you compare the word[i] to " " you try to compare a char to a string
+ 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;
+ 1
I have used .equals method in java for string n char search any such method in c#.
+ 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;
}
}
+ 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.
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
0
Perhaps pass could be initialized to being false. I do not know how C# handles variables that are not initialized.
0
Never delete a code, always search the mistake, else you never gonna learn and never progresse
0
first you have do remove the first if statement wich is useless and alter the else if to if
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