Can't compare a string to an *?
I am having a weird problem here. I am reading in a csv and one of the values is an . When I log the value to the console, I see an logged, but if I try to something like
string[] s = line.Split(delims);
Debug.Log(s[2] + " " + s[2].Equals("*"));
The output I get is
* false
From the logs, s[2] is clearly , but Equals isn't working. I thought I might need to escape the with a \, but that won't compile.
I even tried to check the encoding with
Debug.Log(System.Text.Encoding.ASCII.GetBytes(s[2])[0] + " " + System.Text.Encoding.ASCII.GetBytes("*")[0]);
And both print out 42!
Answer by Habitablaba · Jun 24, 2016 at 09:56 PM
does s[2] actually have leading or trailing white space? What happens if you call
Debug.Log(s[2].Trim() + " " + s[2].Trim().Equals("*"));
Edit: changed where the trim goes, so it actually makes sense.
I thought I had checked that by logging a . immediately after s[2] in my debug log and there was not a space, but somehow an invisible one was there. Using Trim fixed it. Thanks!
If you make this an answer, I can mark it accepted.
Answer by jgodfrey · Jun 24, 2016 at 09:57 PM
A character and a string are not the same thing. In your code, this...
s[2]
Is a character. However, this:
"*"
is a string.
You probably want this:
s[2].Equals('*');
Which compares the value of element #2 to the character '*'.
Split returns and array of strings so s is an array of strings. So I want s[2].Equals("*");