From time to time I get an error when comparing two strings. One is saved as a string type in the app, the other is read from a .txt file. In some cases, the code result is that the strings do not match, but when I physically look at the output (done as a message box), the strings are identical.
Dim ControllerSn As String
If Trim( App.ControllerSN) <> Trim(ControllerSn) then
What is the best & proper way to compare two sets of strings? These are all alpha numeric ascii characters.
Remember that String is a bucket of bytes. It’s literally a string of sequential bytes. So, while they may visually look similar, there are non-visual aspects that are part of the comparison, whether you use StrComp as suggested or the regular operator.
The implementation of how you’re comparing the strings needs to be specific to what you’re trying to do.
Make sure you define the encoding of the string that you read from the file.
And msgbox both the string and it’s Hex values. That will show up any stray bytes that would cause a mismatch.
What is the most appropriate encoding to use?
I am certainly only a novice in this area but use whatever encoding the file was written with. If that’s different from the encoding of the strings in your app then you would need to convert so you’re comparing like-for-like.
In most cases, though you should probably be ok trying UTF8 if it’s just simple ASCII text.
I both write the file and read it. But the encoding is not specified.
Is there a default?
Do the strings need to be converted to “text” first, or just use strcomp as Roger suggested?
To be honest, I’m still a bit new at this myself. I think most Xojo strings default to UTF8 but I had a problem recently because I was reading a string over a TCPSocket. The string was being sent by another Xojo program but the string was read from a file created by a different, non-Xojo app. I found that the string coming over had no encoding.
When I forced UTF8 encoding in the socket’s ReadAll method the problem vanished.
Put in a breakpoint when you load the string from the file and examine the string in the watch window (with the magnifying glass icon). You should see whether or not it has any encoding. If it has none try setting the encoding property of the TextInputStream (use UTF8) and see if that helps.
String literals are UTF8. But be aware that strings get the lowest common denominator encoding. If you acquire a string from outside your app, it will have no encoding. So if you then append it to another string, the result will have a nil encoding as well. That said, most likely, the string you wrote to the file was UTF8. So use that as the encoding you read back in.
On the other hand, you said the contents were pure ASCII, so encoding wouldn’t be the issue. There may be other bytes mixed in to the string that are causing a problem. Check the hex values of the two strings to find the issue.