string comparison

H

Harold Hsu

Hi all,

We have a piece of code that reads data from SQL Server and data from
Oracle. They are both strings. We are trying to compare the two strings
(dr(column).ToString()) for equality. When we display the string on screen,
they are the same. But when we try str1.CompareTo(str2), it returns -1. We
tried the following and they all return -1:

StrComp(str1, str2, CompareMethod.Text)
StrComp(str1, str2, CompareMethod.Binary)
String.Compare(str1, str2, true,
System.Globalization.CultureInfo.InvariantCulture)

But when we do a char by char comparision, all chars are equal.

Any suggestions on what might be the problem? I don't even know if it has
anything to do with the databases.

Thanks,
Harold
 
J

Jay B. Harlow [MVP - Outlook]

Harold,
Does one of the strings (str2 specifically) have trailing spaces on it?

What does "str1.Length.CompareTo(str2.Length)" return. I suspect it will
be -1 also.

Hope this helps
Jay
 
H

Harold Hsu

The original code was doing this:

If Trim(str1) = Trim(str2) Then ...

It didn't work, and that's why we try CompareTo(). Is "=" only doing a
reference comparison?

Harold
 
J

Jay B. Harlow [MVP - Outlook]

Harold,
Again, What does "str1.Length.CompareTo(str2.Length)" return?


"=" does Microsoft.VisualBasic.CompilerServices.StringType::StrCmp, which
does NOT do a reference equals!

For example:

Dim str1 As String = New String("a"c, 10)
Dim str2 As String = New String("a"c, 10)

Debug.WriteLine(str1 = str2, "=")
Debug.WriteLine(str1 Is str2, "reference")


It may be some other characters that Trim is not removing, that you normally
"don't" see.

Which is why I am asking what does "str1.Length.CompareTo(str2.Length)"
return!

Also what does the following return?

For Each ch As Char In str1
Debug.WriteLine(ch, AscW(ch).ToString())
Next
Debug.WriteLine(Nothing)
For Each ch As Char In str2
Debug.WriteLine(ch, AscW(ch).ToString())
Next

Which prints each character, plus its unicode code point.

Hope this helps
Jay
 
H

Harold Hsu

Hi Jay,

Unfortunately, I don't have access to the code. The code only works on
production server because only the production server has access to the
database. I was shown the code and asked if I know why it didn't
work...which triggers my curiosity.

Thanks for the ideas though!

Harold
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top