StrComp function compares two Strings and returns the Boolean values.
Syntax: StrComp(String1,String2,[Compare])
String1 (Required) – String expression
String2 (Required) – String expression
Compare (Optional) – Specifies the type of comparison to be performed. It takes the
below two values –
0 (VbBinaryCompare) – Performs Binary comparison
1 (VbTextCompare) – Performs Text comparison
If not specified, it performs Binary
comparison by default.
Return Values:
StrComp function returns the following values –
-1 - If String1 < String2
0 - If String1 = String2
1 - If String1 > String2
Examples:
MsgBox StrComp("QTP","QTP
Sreenu") 'Output is "-1" (String1 < String2)
MsgBox StrComp("QTP
Sreenu","QTP Sreenu") 'Output is "0"
(String1 = String2)
MsgBox StrComp("QTP
Sreenu","QTP") 'Output is "1" (String1 > String2)
MsgBox StrComp("QTP
Sreenu","Sreenu") 'Output is "-1" (String1 < String2)
MsgBox StrComp("QTP","qtp",0)
'Output is "-1"
(Binary Comparison)
MsgBox StrComp("QTP","qtp",1)
'Output is "-1"
(Text Comparison)
There might be some confusion on how greater than and less than
operations work for Strings. Even I was having the same confusion and did some
analysis. Here are the outcomes of my analysis –
Let us start the analysis with few examples -
MsgBox StrComp("AB","BA") 'Output is "-1"
MsgBox StrComp("AB","AC") 'Output is "-1"
MsgBox StrComp("ABC","AB") 'Output is "1"
MsgBox StrComp("QTP","AQTP") 'Output is "1"
From the above examples, we can clearly notice that the
comparison starts from the first character of both Strings and executes
character by character until any mismatch is found.
The comparison works with the below principle -
If the
first characters of both Strings are not same – then ASCII values of
both characters would be compared and the result would be displayed. The
Comparison ends there itself, and does not bother about the remaining
characters of the String, how big is the String though.
Msgbox StrComp("B","ABCDEFGHIJKLM") 'Output is "1"
(B>A)
If the
first characters of both Strings are same - then the comparison
starts from second character and so on until it finds any mismatch. If all
characters are same then the comparison result is 0.
Msgbox StrComp("ABCDEFGHIJKLM","ABD")
'Output is "-1" (C<D)
No comments:
Post a Comment