Hi all,
I’m shocked and appalled at myself for having to ask about this, but I’m getting nowhere. Basically, I’m having trouble comparing two strings in C#. Yes, you read that right, it’s something I must have done hundreds of times in my project before, but for some reason, I’m not getting the results I’m expecting.
To keep it short, I’ve got two variables, one of these comes from PlayerPrefs, the other is read from a external file on the hard drive. I’m comparing them, then doing what I need to do depending on the result, easy, right?
So far I’ve tried:
if(str1 == str2){
// do stuff
}
else {
// do other stuff
}
Also
if(string.Equals(str1, str2)){
// do stuff
}
else {
// do other stuff
}
Theres no problem with the code here, theres no errors in it and it works as you would expect- depending on the contents of the string. To explain- when the contents of str1 and str2 are “BARNEY”, the comparison is true, and the expected code executes. However, if the contents are “M DOG”, the comparison fails, every single time. Even when I debug log the contents of the string, they look exactly the same to me, but the comparison fails.
So I put my thinking cap on. A wild stab in the dark, I thought maybe it’s the blank space giving me problems, it was worth a shot. So I used str1.Replace(" ", string.Empty) and did the same for str2. But I get the same results, the space is gone, the strings look equal in the console, but the function comparing them is still returning false every time.
I tried replacing the contents of the variables manually, instead of from the text file and from player prefs, and the comparison works flawlessly. So I guess I’m asking is there something happening that could make two strings appear the same to me, but not to my code, when one is read from a text file and one is from playerprefs?
Things I haven’t tried:
- Asking my cat
- Throwing my machine out the window
- Making a thread comparing Unity to UE
Thanks for any input, solutions or out right mockery (I kinda deserve it)!