if (string[i]=="f") doesn'work -string, char type mismatch

  • Thread starter Thread starter beginner
  • Start date Start date
B

beginner

please help me.

can't cast char to string , or something like that - can't remember
exactly and not on my .net pc. But basically, i thought that "x" would be
treated as a char in this case and if not what am i supposed to compare
string[i[ (or any other chars) to - ascii codes?

many thanks
 
Hi Anon?
to check for a specific character in a string you should use a syntax like
this:

string s == "something";
char c = 'f'; // <--- notice the single quotes!!!

if (s.toCharArray[3] == c)...

to check if to string have the identical content use this:

string s1 = "test";
string s2 = "test";

if (s1.equals(s2)) ...

if (s1 == s2) doesn't work for this problem since it compares the
memory-addresses of the strings.


Greetings,
Matti
 
Matthias said:
Hi Anon?
to check for a specific character in a string you should use a syntax like
this:

string s == "something";
char c = 'f'; // <--- notice the single quotes!!!

if (s.toCharArray[3] == c)...

to check if to string have the identical content use this:

string s1 = "test";
string s2 = "test";

if (s1.equals(s2)) ...

if (s1 == s2) doesn't work for this problem since it compares the
memory-addresses of the strings.

The String class overrides the == operator so it does perform a test for
value equality (the == operator simply calls the Equals() method)

Note that in your sample, s1 and s2 also have reference equality, since
the C# compiler automatically interns string constants.
Greetings,
Matti

please help me.

can't cast char to string , or something like that - can't remember
exactly and not on my .net pc. But basically, i thought that "x" would be
treated as a char in this case and if not what am i supposed to compare
string[i[ (or any other chars) to - ascii codes?

many thanks
 
try == 'f'

thanks. single quotes! - that's what it was.

I had worked out a workaround which was
if(Convert.ToString(string)=="f")

but single quotes is neater and i presume more efficient
 
Back
Top