String comparison: Difference between revisions

Add Ecstasy example
(Add Avail entry)
(Add Ecstasy example)
 
(48 intermediate revisions by 35 users not shown)
Line 1:
{{task|Basic Data Operations}}{{basic data operation}} [[Category:Basic language learning]] [[Category:Simple]]
{{basic data operation}}
The task is to demonstrate how to compare two strings from within the language and how to achieve a lexical comparison.
[[Category:Basic language learning]]
[[Category:Simple]]
 
;Task:
Demonstrate how to compare two strings from within the language and how to achieve a lexical comparison.
 
 
The task should demonstrate:
Line 9 ⟶ 15:
* How to achieve both case sensitive comparisons and case insensitive comparisons within the language
* How the language handles comparison of numeric strings if these are not treated lexically
* Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system.   For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction.
 
 
For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction.
 
<br>
Line 17 ⟶ 26:
 
 
{{Template:Strings}}
;Related tasks:
* &nbsp; [[Integer comparison]]
* &nbsp; [[String matching]]
* &nbsp; [[Compare a list of strings]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
Note: 11l does not have case-insensitive string comparison operators, instead use <code>name.upper()</code> or <code>name.lower()</code> to coerce strings to the same case and compare the results.
 
<syntaxhighlight lang="11l">F compare(a, b)
I a < b {print(‘'#.' is strictly less than '#.'’.format(a, b))}
I a <= b {print(‘'#.' is less than or equal to '#.'’.format(a, b))}
I a > b {print(‘'#.' is strictly greater than '#.'’.format(a, b))}
I a >= b {print(‘'#.' is greater than or equal to '#.'’.format(a, b))}
I a == b {print(‘'#.' is equal to '#.'’.format(a, b))}
I a != b {print(‘'#.' is not equal to '#.'’.format(a, b))}
 
compare(‘YUP’, ‘YUP’)
compare(‘BALL’, ‘BELL’)
compare(‘24’, ‘123’)</syntaxhighlight>
 
{{out}}
<pre>
'YUP' is less than or equal to 'YUP'
'YUP' is greater than or equal to 'YUP'
'YUP' is equal to 'YUP'
'BALL' is strictly less than 'BELL'
'BALL' is less than or equal to 'BELL'
'BALL' is not equal to 'BELL'
'24' is strictly greater than '123'
'24' is greater than or equal to '123'
'24' is not equal to '123'
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program comparString64.s */
Line 205 ⟶ 242:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC TestEqual(CHAR ARRAY s1,s2)
INT res
 
PrintF("""%S"" and ""%S"" are equal: ",s1,s2)
IF SCompare(s1,s2)=0 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC TestInequal(CHAR ARRAY s1,s2)
INT res
 
PrintF("""%S"" and ""%S"" are inequal: ",s1,s2)
IF SCompare(s1,s2)#0 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC TestBefore(CHAR ARRAY s1,s2)
INT res
 
PrintF("""%S"" is before ""%S"": ",s1,s2)
IF SCompare(s1,s2)<0 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC TestAfter(CHAR ARRAY s1,s2)
INT res
 
PrintF("""%S"" is after ""%S"": ",s1,s2)
IF SCompare(s1,s2)>0 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC TestNumEqual(CHAR ARRAY s1,s2)
INT v1,v2
 
PrintF("""%S"" and ""%S"" are equal: ",s1,s2)
v1=ValI(s1) v2=ValI(s2)
IF v1=v2 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC TestNumInequal(CHAR ARRAY s1,s2)
INT v1,v2
 
PrintF("""%S"" and ""%S"" are inequal: ",s1,s2)
v1=ValI(s1) v2=ValI(s2)
IF v1#v2 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC TestNumBefore(CHAR ARRAY s1,s2)
INT v1,v2
 
PrintF("""%S"" is before ""%S"": ",s1,s2)
v1=ValI(s1) v2=ValI(s2)
IF v1<v2 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC TestNumAfter(CHAR ARRAY s1,s2)
INT v1,v2
 
PrintF("""%S"" is after ""%S"": ",s1,s2)
v1=ValI(s1) v2=ValI(s2)
IF v1>v2 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
 
PROC Main()
PrintE("Lexical comparison:")
TestEqual("abcd","Abcd")
TestInequal("abcd","Abcd")
TestBefore("abcd","Abcd")
TestAfter("abcd","Abcd")
PutE()
 
PrintE("Numerical comparison:")
TestNumEqual("1234","99876")
TestNumInequal("1234","99876")
TestNumBefore("1234","99876")
TestNumAfter("1234","99876")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/String_comparison.png Screenshot from Atari 8-bit computer]
<pre>
Lexical comparison:
"abcd" and "Abcd" are equal: False
"abcd" and "Abcd" are inequal: True
"abcd" is before "Abcd": False
"abcd" is after "Abcd": True
 
Numerical comparison:
"1234" and "99876" are equal: False
"1234" and "99876" are inequal: True
"1234" is before "99876": False
"1234" is after "99876": True
</pre>
 
=={{header|Ada}}==
Ada uses the usual comparison operators ("=" for equality, "/=" for not being equal, etc.) for strings. One uses the same comparison operators to compare variables of other types (integers, floating point numbers, etc.).
Line 213 ⟶ 374:
String comparisons are case sensitive. Case insensitive comparisons have to use some conversion operation, such as Ada.Characters.Handling.To_Lower from the standard library, cf. [[http://rosettacode.org/wiki/String_case#Ada]]
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Strings.Equal_Case_Insensitive;
 
procedure String_Compare is
Line 240 ⟶ 401:
Print_Comparison ("the", "there");
Print_Comparison ("there", "the");
end String_Compare;</langsyntaxhighlight>
 
{{out}}
Line 252 ⟶ 413:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">text s, t;
 
s = "occidental";
Line 267 ⟶ 428:
 
# case insensitive comparison
o_form("~ vs ~ (==, !=, <, >): ~ ~ ~ ~\n", s, t, !icompare(s, t), icompare(s, t), icompare(s, t) < 0, 0 < icompare(s, t));</langsyntaxhighlight>
{{out}}
<pre>occidental vs oriental (==, !=, <, <=, >=, >): 0 -15 1 1 0 0
Line 275 ⟶ 436:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68">STRING a := "abc ", b := "ABC ";
 
# when comparing strings, Algol 68 ignores trailing blanks #
Line 341 ⟶ 502:
test( a >= b, "a >= b" );
 
# there are no other forms of string comparison builtin to Algol 68 #</langsyntaxhighlight>
{{out}}
<pre>
Line 351 ⟶ 512:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
string(10) a;
string(12) b;
Line 417 ⟶ 578:
% there are no other forms of string comparison builtin to Algol W %
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 431 ⟶ 592:
Comparisons can be done also using the equals(), equalsIgnoreCase() and compareTo() methods.
 
<langsyntaxhighlight lang="java">public class Compare
{
/**
Line 465 ⟶ 626:
System.debug('The lexical relationship is: ' + A.compareTo(B));
}
}</langsyntaxhighlight>
 
{{Out}}
Line 496 ⟶ 657:
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">--Comparing two strings for exact equality
set s1 to "this"
set s2 to "that"
Line 547 ⟶ 708:
if int1 < s1 then
-- comparison is numeric
end if</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program comparString.s */
Line 732 ⟶ 893:
bx lr /* end procedure */
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">loop [["YUP" "YUP"] ["YUP" "Yup"] ["bot" "bat"] ["aaa" "zz"]] 'x [
print [x\0 "=" x\1 "=>" x\0 = x\1]
print [x\0 "=" x\1 "(case-insensitive) =>" (upper x\0) = upper x\1]
print [x\0 "<>" x\1 "=>" x\0 <> x\1]
print [x\0 ">" x\1 "=>" x\0 > x\1]
print [x\0 ">=" x\1 "=>" x\0 >= x\1]
print [x\0 "<" x\1 "=>" x\0 < x\1]
print [x\0 "=<" x\1 "=>" x\0 =< x\1]
print "----"
]</syntaxhighlight>
 
{{out}}
 
<pre>YUP = YUP => true
YUP = YUP (case-insensitive) => true
YUP <> YUP => false
YUP > YUP => false
YUP >= YUP => true
YUP < YUP => false
YUP =< YUP => true
----
YUP = Yup => false
YUP = Yup (case-insensitive) => true
YUP <> Yup => true
YUP > Yup => false
YUP >= Yup => false
YUP < Yup => true
YUP =< Yup => true
----
bot = bat => false
bot = bat (case-insensitive) => false
bot <> bat => true
bot > bat => true
bot >= bat => true
bot < bat => false
bot =< bat => false
----
aaa = zz => false
aaa = zz (case-insensitive) => false
aaa <> zz => true
aaa > zz => false
aaa >= zz => false
aaa < zz => true
aaa =< zz => true
----</pre>
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">fun compare(a, b):
print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}")
if a < b: print("$a is strictly less than $b")
Line 751 ⟶ 959:
compare(24, 123)
compare(5.0, 5)
</syntaxhighlight>
</lang>
 
=={{header|Avail}}==
<langsyntaxhighlight Availlang="avail">Method "string comparisons_,_" is
[
a : string,
Line 769 ⟶ 977:
// Case-insensitive comparison requires a manual case conversion
Print: "a & b are equal case-insensitively?" ++ “lowercase a = lowercase b”;
];</langsyntaxhighlight>
Avail is strongly-typed and the standard library's comparison functions do not admit mixed comparison between numerics and strings. Strings are immutable tuples of characters and are always compared by value -- few entities in Avail have identity so "object equality" is usually meaningless.
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">exact_equality(a,b){
return (a==b)
}
exact_inequality(a,b){
return !(a==b)
}
equality(a,b){
return (a=b)
}
inequality(a,b){
return !(a=b)
}
ordered_before(a,b){
return ("" a < "" b)
}
ordered_after(a,b){
return ("" a > "" b)
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">for a, b in {"alpha":"beta", "Gamma":"gamma", 100:5}
MsgBox % a " vs " b "`n"
. "exact_equality case sensitive : " exact_equality(a,b) "`n"
. "exact_inequality case sensitive :" exact_inequality(a,b) "`n"
. "equality case insensitive : " equality(a,b) "`n"
. "inequality case insensitive : " inequality(a,b) "`n"
. "ordered_before : " ordered_before(a,b) "`n"
. "ordered_after : " ordered_after(a,b) "`n"</syntaxhighlight>
{{out}}
<pre>100 vs 5
exact_equality case sensitive : 0
exact_inequality case sensitive :1
equality case insensitive : 0
inequality case insensitive : 1
ordered_before : 1
ordered_after : 0
---------------------------
alpha vs beta
exact_equality case sensitive : 0
exact_inequality case sensitive :1
equality case insensitive : 0
inequality case insensitive : 1
ordered_before : 1
ordered_after : 0
---------------------------
Gamma vs gamma
exact_equality case sensitive : 0
exact_inequality case sensitive :1
equality case insensitive : 1
inequality case insensitive : 0
ordered_before : 0
ordered_after : 0</pre>
 
=={{header|AWK}}==
Line 779 ⟶ 1,039:
The behaviour of the operators when one value is considered to be numeric (eg. from the input source), but the other value has been defined explicitly as a numeric string by using doublequote enclosures may also vary depending on which awk interpreter is being used.
 
<langsyntaxhighlight lang="awk">BEGIN {
a="BALL"
b="BELL"
Line 795 ⟶ 1,055:
if (tolower(a) == tolower(b)) { print "The first and second string are the same disregarding letter case" }
 
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="basic">10 LET "A$="BELL"
20 LET B$="BELT"
30 IF A$ = B$ THEN PRINT "THE STRINGS ARE EQUAL": REM TEST FOR EQUALITY
Line 806 ⟶ 1,066:
70 IF A$ <= B$ THEN PRINT A$;" IS NOT LEXICALLY HIGHER THAN ";B$
80 IF A$ >= B$ THEN PRINT A$;" IS NOT LEXICALLY LOWER THAN ";B$
90 END</langsyntaxhighlight>
 
On a platform that supports both uppercase and lowercase characters, the string comparitive operators are case sensitive. To perform case insensitive matching, make sure both strings are converted to the same lettercase. Here we assume that the BASIC has the UPPER$ and LOWER$ keyword pair for case conversion. If not, then some number crunching based on the character codes is required. (In Ascii add 32 to uppercase letter codes to get the lowercase equivalent). Note that any whitespace within the strings must also match exactly for the strings to be considered equal.
 
<langsyntaxhighlight lang="basic">10 LET A$="BELT"
20 LET B$="belt"
30 IF UPPER$(A$)=UPPER$(B$) THEN PRINT "Disregarding lettercase, the strings are the same."</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
Line 818 ⟶ 1,078:
Applesoft BASIC does not have a built in UPPER$ function.
 
==={{header|BBC BASICBASIC256}}===
{{trans|FreeBASIC}}
<lang bbcbasic>REM >strcomp
<syntaxhighlight lang="freebasic">function StringCompare(s1, s2, ignoreCase)
if ignoreCase then
s = lower(s1)
t = lower(s2)
else
s = s1
t = s2
end if
if s < t then return " comes before "
if s = t then return " is equal to "
return " comes after "
end function
 
s1 = "Dog" : s2 = "Dog"
print s1; StringCompare(s1, s2, False); s2
s2 = "Cat"
print s1; StringCompare(s1, s2, False); s2
s2 = "Rat"
print s1; StringCompare(s1, s2, False); s2
s2 = "dog"
print s1; StringCompare(s1, s2, False); s2
print s1; StringCompare(s1, s2, True); s2; " if case is ignored"
s1 = "Dog" : s2 = "Pig"
s3 = StringCompare(s1, s2, False)
if s3 <> " is equal to " then print s1; " is not equal to "; s2
end</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic">REM >strcomp
shav$ = "Shaw, George Bernard"
shakes$ = "Shakespeare, William"
Line 847 ⟶ 1,138:
IF ASC(MID$(s$, i%, 1)) >= ASC "a" AND ASC(MID$(s$, i%, 1)) <= ASC "z" THEN ns$ += CHR$(ASC(MID$(s$, i%, 1)) - &20) ELSE ns$ += MID$(s$, i%, 1)
NEXT
= ns$</langsyntaxhighlight>
{{out}}
<pre>The two strings are not equal
Line 854 ⟶ 1,145:
Shaw, George Bernard is not lexically lower than Shakespeare, William
The two strings are not equal (even disregarding case)</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">FUNCTION StringCompare$ (s1 AS STRING, s2 AS STRING, ignoreCase)
DIM s AS STRING, t AS STRING
IF ignoreCase THEN
s = LCASE$(s1)
t = LCASE$(s2)
ELSE
s = s1
t = s2
END IF
IF s < t THEN StringCompare$ = " comes before ": EXIT FUNCTION
IF s = t THEN StringCompare$ = " is equal to ": EXIT FUNCTION
StringCompare$ = " comes after "
END FUNCTION
 
DIM s1 AS STRING, s2 AS STRING, s3 AS STRING
 
s1 = "Dog": s2 = "Dog"
PRINT s1; StringCompare$(s1, s2, 0); s2
s2 = "Cat"
PRINT s1; StringCompare$(s1, s2, 0); s2
s2 = "Rat"
PRINT s1; StringCompare$(s1, s2, 0); s2
s2 = "dog"
PRINT s1; StringCompare$(s1, s2, 0); s2
PRINT s1; StringCompare$(s1, s2, 1); s2; " if case is ignored"
s1 = "Dog": s2 = "Pig"
s3 = StringCompare$(s1, s2, 0)
IF s3 <> " is equal to " THEN PRINT s1; " is not equal to "; s2
END</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
==={{header|True BASIC}}===
{{works with|QBasic}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">FUNCTION StringCompare$(s1$, s2$, ignorecase)
IF ignorecase = True then
LET s$ = LCASE$(s1$)
LET t$ = LCASE$(s2$)
ELSE
LET s$ = s1$
LET t$ = s2$
END IF
IF s$ < t$ then
LET StringCompare$ = " comes before "
ELSE
IF s$ = t$ then
LET StringCompare$ = " is equal to "
ELSE
LET StringCompare$ = " comes after "
END IF
END IF
END FUNCTION
 
LET s1$ = "Dog"
LET s2$ = "Dog"
PRINT s1$; StringCompare$(s1$, s2$, False); s2$
LET s2$ = "Cat"
PRINT s1$; StringCompare$(s1$, s2$, False); s2$
LET s2$ = "Rat"
PRINT s1$; StringCompare$(s1$, s2$, False); s2$
LET s2$ = "dog"
PRINT s1$; StringCompare$(s1$, s2$, False); s2$
PRINT s1$; StringCompare$(s1$, s2$, True); s2$; " if case is ignored"
LET s1$ = "Dog"
LET s2$ = "Pig"
LET s3$ = StringCompare$(s1$, s2$, 0)
IF s3$ <> " is equal to " then PRINT s1$; " is not equal to "; s2$
END</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="freebasic">sub StringCompare$(s1$, s2$, ignoreCase)
local s$, t$
if ignoreCase then
s$ = lower$(s1$)
t$ = lower$(s2$)
else
s$ = s1$
t$ = s2$
end if
if s$ < t$ return " comes before "
if s$ = t$ return " is equal to "
return " comes after "
end sub
 
s1$ = "Dog" : s2$ = "Dog"
print s1$, StringCompare$(s1$, s2$, False), s2$
s2$ = "Cat"
print s1$, StringCompare$(s1$, s2$, False), s2$
s2$ = "Rat"
print s1$, StringCompare$(s1$, s2$, False), s2$
s2$ = "dog"
print s1$, StringCompare$(s1$, s2$, False), s2$
print s1$, StringCompare$(s1$, s2$, True), s2$, " if case is ignored"
s1$ = "Dog" : s2$ = "Pig"
s3$ = StringCompare$(s1$, s2$, False)
if s3$ <> " is equal to " print s1$, " is not equal to ", s2$
end</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
==={{header|uBasic/4tH}}===
{{works with|R4}}
uBasic/4tH provides a builtin, case insensitive function to compare two strings, called <code>COMP()</code> which returns either a negative, zero or positive value, just like <code>strcmp()</code>. In order to compare two strings case sensitive, a user defined function is required.
<syntaxhighlight lang="text">Print "Case sensitive"
Print "=============="
Print Show (FUNC(_Eval(FUNC(_StrCmp ("Dog", "Dog")))))
Print Show (FUNC(_Eval(FUNC(_StrCmp ("Dog", "Cat")))))
Print Show (FUNC(_Eval(FUNC(_StrCmp ("Dog", "Rat")))))
Print Show (FUNC(_Eval(FUNC(_StrCmp ("Dog", "dog")))))
Print Show (FUNC(_Eval(FUNC(_StrCmp ("Dog", "Pig")))))
 
Print
 
Print "Case insensitive"
Print "================"
Print Show (FUNC(_Eval(Comp ("Dog", "Dog"))))
Print Show (FUNC(_Eval(Comp ("Dog", "Cat"))))
Print Show (FUNC(_Eval(Comp ("Dog", "Rat"))))
Print Show (FUNC(_Eval(Comp ("Dog", "dog"))))
Print Show (FUNC(_Eval(Comp ("Dog", "Pig"))))
 
End
 
_StrCmp ' case sensitive compare
Param (2)
Local (3)
' up to the maximum length
For c@ = 0 To Max (Len (a@), Len (b@)) - 1
d@ = Iif (c@ < Len (a@), Peek (a@, c@), 0)
e@ = Iif (c@ < Len (b@), Peek (b@, c@), 0)
While (d@ = e@) ' while retrieved characters are equal
Next
 
Return (d@ - e@) ' return comparison
 
_Eval ' evaluate result
Param (1)
If a@ = 0 Then Return ("Equal")
If a@ > 0 Then Return ("Second before First")
Return ("First before Second")</syntaxhighlight>
Output:
<pre>
Case sensitive
==============
Equal
Second before First
First before Second
First before Second
First before Second
 
Case insensitive
================
Equal
Second before First
First before Second
Equal
First before Second
 
0 OK, 0:673
</pre>
 
=={{header|Bracmat}}==
String comparison in Bracmat is performed by string pattern matching using an atomic pattern. Bracmat has two pattern matching regimes. Originally, pattern matching was only done on tree structures, with patterns mimicking the subject tree to match. Later string pattern matching was introduced. String pattern matching is discernible from the original pattern matching by the prefix <code>@</code>. String pattern matching requires that the subject is atomic. Patterns for string matching can be as complex as patterns used for matching structures. String comparison is a very simple string pattern matching operation requiring just an atomic pattern, combined with some prefixes if needed.
The atomic pattern can be prefixed with <code>&lt;</code> (less than), <code>&gt;</code> (greater than), <code>~</code> (not) or <code>%</code> (coerces string matching) or combinations thereof. If both sides of the match operator <code>:</code> are numbers, Bracmat does a numerice comparison, unless the pattern (the rhs) has the prefix <code>%</code>.
<langsyntaxhighlight lang="bracmat">( {Comparing two strings for exact equality}
& ( ( @(abc:abc)
& @(123:%123)
Line 959 ⟶ 1,419:
)
& done
);</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) "abc""abc"==
1
Line 972 ⟶ 1,432:
blsq ) "ABC""Abc"cm
-1
</syntaxhighlight>
</lang>
 
''cm'' is used for comparision which returns 1,0,-1 like C's strcmp. ''=='' is Equal and ''!='' is NotEqual.
Line 979 ⟶ 1,439:
'''Solution'''
C provides the strcmp and strcasecmp functions for lexical comparison of ASCIIz strings, with declarations found in string.h . strcmp causes a good deal of confusion because it returns 0 when the strings are equal. Hence the likely looking common mistake
<syntaxhighlight lang="c">
<lang c>
/* WRONG! */
if (strcmp(a,b)) action_on_equality();
</syntaxhighlight>
</lang>
Wrapping strcmp with macros or functions makes good sense. c has other functions to compare binary data, version strings, wide character strings, and strings in current locale. These behave similarly.
<syntaxhighlight lang="c">
<lang c>
/*
compilation and test in bash
Line 1,046 ⟶ 1,506:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <sstream>
Line 1,087 ⟶ 1,547:
demo_compare<double>(numA, numB, "numerically");
return (a == b);
}</langsyntaxhighlight>
{{out}}
<pre>1.2.Foo and 1.3.Bar are not exactly lexically equal.
Line 1,104 ⟶ 1,564:
=={{header|Clipper}}==
We will compare two strings, ''s1'' and ''s2''. The following comparisons are case sensitive.
<langsyntaxhighlight lang="clipper"> IF s1 == s2
? "The strings are equal"
ENDIF
Line 1,115 ⟶ 1,575:
IF s1 < s2
? "s2 is lexically ordered after than s1"
ENDIF</langsyntaxhighlight>
To achieve case insensitive comparisons, we should use Upper() or Lower() functions:
<langsyntaxhighlight lang="clipper"> IF Upper(s1) == Upper(s2)
? "The strings are equal"
ENDIF
</syntaxhighlight>
</lang>
 
 
=={{header|Clojure}}==
To do basic equality checks, the standard '=' operator works fine. It will do case-sensitive comparisons. To test for inequality, if simply changing the logic of your conditional isn't desirable, there is the 'not=' operator.
 
<syntaxhighlight lang="clojure">(= "abc" "def") ; false
(= "abc" "abc") ; true
 
(not= "abc" "def") ; true
(not= "abc" "abc") ; false</syntaxhighlight>
 
One of the benefits of the core '=' operator is that it is "variadic", so you can use it to test for equality of an arbitrary number of strings.
 
<syntaxhighlight lang="clojure">(= "abc" "abc" "abc" "abc") ; true
(= "abc" "abc" "abc" "def") ; false</syntaxhighlight>
 
If you want to test whether all the strings in a 'collection' (e.g. vector, list, sequence) are equal to one another, 'apply' is your friend.
 
<syntaxhighlight lang="clojure">(apply = ["abc" "abc" "abc" "abc"]) ; true</syntaxhighlight>
 
To check whether a given string is lexically before or after another, we could create functions like these, utilizing the core 'compare' function. The same compare function is used by default when one calls 'sort'.
 
<syntaxhighlight lang="clojure">(defn str-before [a b]
(neg? (compare a b)))
 
(defn str-after [a b]
(pos? (compare a b)))
 
(str-before "abc" "def") ; true
(str-before "def" "abc") ; false
(str-before "abc" "abc") ; false
 
(str-after "abc" "def") ; false
(str-after "def" "abc") ; false
 
(sort ["foo" "bar" "baz"]) ; ("bar" "baz" "foo")</syntaxhighlight>
 
If want a case-insensitive comparison, you need to up-case or down-case the input strings.
 
<syntaxhighlight lang="clojure">(defn str-caseless= [a b]
(= (clojure.string/lower-case a)
(clojure.string/lower-case b)))
 
(str-caseless= "foo" "fOO") ; true</syntaxhighlight>
 
This next example is contrived, but shows a bit of how you could create a "fuzzy compare" that might apply in some real case you have. For this example, we have some data which you might imagine being related to a report containing numeric values, some are actual numbers, some string representations, strings in some cases have leading or trailing whitespace. We want to get rid of whitespace, convert any number-types to string form, and then compare for equality. Note that some of the values we want to compare are integers, some are floating point values, and some aren't numeric at all.
 
<syntaxhighlight lang="clojure">(defn str-fuzzy= [a b]
(let [cook (fn [v] (clojure.string/trim (str v)))]
(= (cook a) (cook b))))
 
(str-fuzzy= "abc" " abc") ; true
(str-fuzzy= "abc" "abc ") ; true
(str-fuzzy= "abc" " abc ") ; true
 
(str-fuzzy= " 42 " 42) ; true
(str-fuzzy= " 42 " (* 6 7)) ; true
 
(str-fuzzy= " 2.5" (/ 5.0 2)) ; true</syntaxhighlight>
 
Most of the time when we compare strings, we care about whether they "look the same" and Clojure's core '=' operator uses this logic. In some cases, though, we care about whether 2 strings actually reside in the same memory location. We can check this with the 'identical?' function.
 
<syntaxhighlight lang="clojure">(def s1 (str "abc" "def"))
(def s2 (str "ab" "cdef"))
 
(= s1 "abcdef") ; true
(= s1 s2) ; true
 
(identical? s1 "abcdef") ; false
(identical? s1 s2) ; false</syntaxhighlight>
 
Clojure (as Java) will generally share a single copy of strings that are in the source code and known at compile time. However, strings constructed at run-time may result in many copies of the "same char sequence". When processing large data files, this can create undesirable waste. We can use Java's 'intern' method on the String class to ensure we get only one copy of each runtime-allocated string.
 
<syntaxhighlight lang="clojure">(defn istr [s]
(.intern s))
 
(def s3 (istr s1))
(def s4 (istr s2))
 
(= s3 s4) ; true
(identical? s3 s4) ; true
</syntaxhighlight>
 
=={{header|COBOL}}==
Strings can be compared using the normal conditional syntax, like so:
<langsyntaxhighlight lang="cobol">"hello" = "hello" *> equality
"helloo" <> "hello" *> inequality
"aello" < "hello" *> lexical ordering</langsyntaxhighlight>
 
COBOL 2002 introduced the intrinsic functions <code>LOCALE-COMPARE</code> and <code>STANDARD-COMPARE</code>, which return one of the strings <code>"="</code>, <code>">"</code> or <code>"<"</code> depending on their parameters.
<langsyntaxhighlight lang="cobol">FUNCTION STANDARD-COMPARE("hello", "hello") *> "="
FUNCTION STANDARD-COMPARE("aello", "hello") *> "<"
FUNCTION STANDARD-COMPARE("hello", "aello") *> ">"</langsyntaxhighlight>
 
Trailing spaces in strings are removed when strings are compared. However, if the strings are then of unequal length, then the shorter string is padded with spaces.
<langsyntaxhighlight lang="cobol">"hello " = "hello" *> True
X"00" > X"0000" *> True</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
Line 1,148 ⟶ 1,690:
===In CFML===
 
<langsyntaxhighlight lang="cfm"><cffunction name="CompareString">
<cfargument name="String1" type="string">
<cfargument name="String2" type="string">
Line 1,171 ⟶ 1,713:
</cfif>
<cfreturn VARIABLES.Result >
</cffunction></langsyntaxhighlight>
 
===In CFScript===
 
<langsyntaxhighlight lang="cfm"><cfscript>
function CompareString( String1, String2 ) {
VARIABLES.Result = "";
Line 1,198 ⟶ 1,740:
return VARIABLES.Result;
}
</cfscript></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 1,204 ⟶ 1,746:
 
Case-sensitive comparison functions:
<langsyntaxhighlight lang="lisp">>(string= "foo" "foo")
T
> (string= "foo" "FOO")
Line 1,221 ⟶ 1,763:
NIL
> (string<= "FOo" "Foo")
1</langsyntaxhighlight>
 
Case-insensitive comparison functions:
<langsyntaxhighlight lang="lisp">> (string-equal "foo" "FOo")
T
> (string-not-equal "foo" "FOO")
Line 1,235 ⟶ 1,777:
3
> (string-not-lessp "baz" "bAr")
2</langsyntaxhighlight>
 
Numeric strings are always compared lexically:
<langsyntaxhighlight lang="lisp">> (string> "45" "12345")
0
> (string> "45" "9")
NIL</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">MODULE StringComparision;
IMPORT StdLog,Strings;
 
Line 1,275 ⟶ 1,817:
END Do;
 
END StringComparision.</langsyntaxhighlight>
Execute: ^Q StringComparision.Do<br/>
Output:
Line 1,293 ⟶ 1,835:
=={{header|D}}==
See also [[Empty_string]]
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm;
 
void main() {
Line 1,315 ⟶ 1,857:
assert(s.icmp("ABCD") == 0); // case insensitive
assert(s.cmp("ABCD") == 1); // case sensitive
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
 
procedure ShowCompares(Memo: TMemo; S1,S2: string);
begin
if S1=S2 then Memo.Lines.Add(Format('"%s" is exactly equal to "%s"',[S1,S2]));
if S1<>S2 then Memo.Lines.Add(Format('"%s" is not equal to "%s"',[S1,S2]));
if S1<S2 then Memo.Lines.Add(Format('"%s" is less than "%s"',[S1,S2]));
if S1<=S2 then Memo.Lines.Add(Format('"%s" is less than or equal to "%s"',[S1,S2]));
if S1>S2 then Memo.Lines.Add(Format('"%s" is greater than "%s"',[S1,S2]));
if S1>=S2 then Memo.Lines.Add(Format('"%s" is greater than or equal to "%s"',[S1,S2]));
if AnsiSameText(S1, S2) then Memo.Lines.Add(Format('"%s" is case insensitive equal to "%s"',[S1,S2]));
Memo.Lines.Add(Format('"%s" "%s" case sensitive different = %d',[S1,S2,AnsiCompareStr(S1,S2)]));
Memo.Lines.Add(Format('"%s" "%s" case insensitive different = %d',[S1,S2,AnsiCompareText(S1,S2)]));
Memo.Lines.Add(Format('"%s" is found at Index %d in "%s"',[S1,Pos(S1,S2),S2]));
end;
 
 
procedure ShowStringCompares(Memo: TMemo);
begin
ShowCompares(Memo,'Equal', 'Equal');
ShowCompares(Memo,'Case', 'CASE');
ShowCompares(Memo,'91', '1234');
ShowCompares(Memo,'boy', 'cowboy');
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
"Equal" is exactly equal to "Equal"
"Equal" is less than or equal to "Equal"
"Equal" is greater than or equal to "Equal"
"Equal" is case insensitive equal to "Equal"
"Equal" "Equal" case sensitive different = 0
"Equal" "Equal" case insensitive different = 0
"Equal" is found at Index 1 in "Equal"
"Case" is not equal to "CASE"
"Case" is greater than "CASE"
"Case" is greater than or equal to "CASE"
"Case" is case insensitive equal to "CASE"
"Case" "CASE" case sensitive different = -1
"Case" "CASE" case insensitive different = 0
"Case" is found at Index 0 in "CASE"
"91" is not equal to "1234"
"91" is greater than "1234"
"91" is greater than or equal to "1234"
"91" "1234" case sensitive different = 1
"91" "1234" case insensitive different = 1
"91" is found at Index 0 in "1234"
"boy" is not equal to "cowboy"
"boy" is less than "cowboy"
"boy" is less than or equal to "cowboy"
"boy" "cowboy" case sensitive different = -1
"boy" "cowboy" case insensitive different = -1
"boy" is found at Index 4 in "cowboy"
Elapsed Time: 41.211 ms.
 
</pre>
 
=={{header|Dyalect}}==
Line 1,321 ⟶ 1,928:
{{trans|Swift}}
 
<langsyntaxhighlight Dyalectlang="dyalect">func compare(a, b) {
if a == b {
print("'\(a)' and '\(b)' are lexically equal.")
Line 1,343 ⟶ 1,950:
}
}
compare("cat", "dog")</langsyntaxhighlight>
{{Out}}
<pre>'cat' and 'dog' are not lexically equal.
'cat' is lexically before 'dog'.
'cat' is not lexically after 'dog'.
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
a$ = "hello"
if a$ = "hello"
print "equal"
.
if a$ <> "hello2"
print "not equal"
.
if strcmp a$ "hello" = 0
print "equal"
.
if strcmp a$ "world" < 0
print "lexically before"
.
if number "10" > number "2"
print "numerically after"
.
</syntaxhighlight>
 
=={{header|Ecstasy}}==
In Ecstasy, strings are objects, like all values. Any class, including classes like <code>Int</code> and <code>String</code>, can provide operator support by annotating the methods that represent those operators. The result is simple uniformity of how types are defined, including their operators. String comparisons rely on these operators:
 
<syntaxhighlight lang="ecstasy">
module StringComparisons {
void run() {
@Inject Console console;
import ecstasy.collections.CaseInsensitive;
 
String[] tests = ["dog", "cat", "Dog"];
String s1 = tests[0];
for (String s2 : tests) {
// Comparing two strings for exact equality
if (s1 == s2) {
console.print($"{s1} == {s2}");
}
 
// Comparing two strings for inequality
if (s1 != s2) {
console.print($"{s1} != {s2}");
}
 
// Comparing two strings to see if one is lexically ordered
// before the other
if (s1 < s2) {
console.print($"{s1} < {s2}");
}
 
// Comparing two strings to see if one is lexically ordered
// after the other
if (s1 > s2) {
console.print($"{s1} > {s2}");
}
 
// How to achieve both case sensitive comparisons and case
// insensitive comparisons within the language
 
if (CaseInsensitive.areEqual(s1, s2)) {
console.print($"{s1} == {s2} (case-insensitive)");
} else {
console.print($"{s1} != {s2} (case-insensitive)");
}
 
switch (CaseInsensitive.compare(s1, s2)) {
case Lesser:
console.print($"{s1} < {s2} (case-insensitive)");
break;
case Equal:
// already covered this one above
assert CaseInsensitive.areEqual(s1, s2);
break;
case Greater:
console.print($"{s1} > {s2} (case-insensitive)");
break;
}
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
dog == dog
dog == dog (case-insensitive)
dog != cat
dog > cat
dog != cat (case-insensitive)
dog > cat (case-insensitive)
dog != Dog
dog > Dog
dog == Dog (case-insensitive)
</pre>
 
=={{header|Elena}}==
ELENA 4.x:
<langsyntaxhighlight lang="elena">import extensions;
compareStrings = (val1,val2)
Line 1,371 ⟶ 2,071:
console.readChar()
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">s = "abcd"
s == "abcd" #=> true
s == "abce" #=> false
Line 1,382 ⟶ 2,082:
s < "abce" #=> true
s >= "abce" #=> false
s <= "abce" #=> true</langsyntaxhighlight>
 
=={{header|Erlang}}==
Examples from Erlang shell:
 
<syntaxhighlight lang="erlang">
<lang Erlang>
10> V = "abcd".
"abcd"
Line 1,400 ⟶ 2,100:
16> string:to_lower(V) =:= string:to_lower("ABCD").
true
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
Line 1,408 ⟶ 2,108:
[http://msdn.microsoft.com/en-us/library/system.stringcomparison StringComparison] enumeration value how to compare, which might be "culture sensitive" or use an "ordinal comparison".
Both of these might also be of the <tt>IgnoreCase</tt> variant.
<langsyntaxhighlight lang="fsharp">open System
 
// self defined operators for case insensitive comparison
Line 1,440 ⟶ 2,140:
compare "24" "123"
compare "BELL" "bELL"
0</langsyntaxhighlight>
Output
<pre style="font-size:smaller">YUP is less than or equal to YUP
Line 1,470 ⟶ 2,170:
Strings in Factor are just sequences of unicode code points, so the usual sequence operations apply to strings. The <tt><=></tt> word from the <tt>math.order</tt> vocabulary can be used to lexically compare strings, and Factor includes the <tt>human<=></tt> word in the <tt>sorting.human</tt> vocabulary for comparing numeric strings like a human would.
 
<langsyntaxhighlight lang="factor">USING: ascii math.order sorting.human ;
 
IN: scratchpad "foo" "bar" = . ! compare for equality
Line 1,487 ⟶ 2,187:
+gt+
IN: scratchpad "a1" "a03" human<=> . ! comparing numeric strings like a human
+lt+</langsyntaxhighlight>
 
=={{header|Falcon}}==
'''VBA/Python programmer's approach. I'm just a junior Falconeer but this code seems to go the falcon way''
<langsyntaxhighlight lang="falcon">
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
Line 1,527 ⟶ 2,227:
result = NumCompare(num1, num2)
> @ "$num1 $result $num2"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,543 ⟶ 2,243:
The ANS Forth standard has the word COMPARE to lexically compare two strings, with the same behavior as the C standard library strcmp() function.
 
<langsyntaxhighlight Forthlang="forth">: str-eq ( str len str len -- ? ) compare 0= ;
: str-neq ( str len str len -- ? ) compare 0<> ;
: str-lt ( str len str len -- ? ) compare 0< ;
: str-gt ( str len str len -- ? ) compare 0> ;
: str-le ( str len str len -- ? ) compare 0<= ;
: str-ge ( str len str len -- ? ) compare 0>= ;</langsyntaxhighlight>
 
Although many Forths allow case-insensitive lookup of ASCII dictionary names for function and variable names (FIND, SEARCH-WORDLIST), this capability is not exposed for other uses in a standard way.
 
=={{header|Fortran}}==
Early Fortran offered no facilities for manipulating text, only numbers, though the FORMAT statement could present text via the "Hollerith" format code of ''n''H, where ''n'' characters follow the H, as in <langsyntaxhighlight Fortranlang="fortran"> PRINT 42,N
42 FORMAT (14HThe answer is ,I9)</langsyntaxhighlight> - though the use of lower-case here is anachronistic. There was an odd facility whereby using such a FORMAT statement in a READ statement would cause the Hollerith text to be replaced by what was read in, and this new text could be written out by a later PRINT statement - but the program could not inspect the text at all. So no string comparison.
 
Fortran IV introduced the A''w'' format code, where ''w'' was an integer such as one or two, and this transferred the bit pattern "as is" to or from a variable in a READ or WRITE statement. A sixteen-bit integer would suit either A1 or A2, a thirty-two bit floating-point variable could hold up to four eight-bit character codes, and so on, though with caution because some computers had eighteen-bit words and others forty-eight bit words, not just powers of two. An array of integers might be used to hold a line of text, and A1 format (one character per integer) would be easier for manipulation, while A2 would use less storage. The variables could be compared as numerical values and so string comparison was possible. However, the numerical values would be quite strange, because A1 format would place the bit pattern at the high-order end of the word (where the sign bit would be found in integers), and with floating-point variables the resulting values would be even more surprising. On the B6700, the high-order bit of a 48-bit word was not employed in arithmetic at all. Even so, in this period, interpreters for SNOBOL (surely the epitome of string-manipulation languages) were often written in Fortran, because of its portability. So, string comparison in the same way as number comparison.
Line 1,569 ⟶ 2,269:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0
 
' Strings in FB natively support the relational operators which compare lexically on a case-sensitive basis.
Line 1,608 ⟶ 2,308:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,619 ⟶ 2,319:
Dog is equal to dog if case is ignored
Dog is not equal to Pig
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn StringComparison
CFStringRef s1, s2
NSComparisonResult result
window 1, @"String Comparison"
print @"• equal - case sensitive •"
s1 = @"alpha" : s2 = @"alpha"
if ( fn StringIsEqual( s1, s2 ) )
printf @"\"%@\" is equal to \"%@\"",s1,s2
end if
result = fn StringCompare( s1, s2 )
if ( result == NSOrderedSame )
printf @"\"%@\" is equal to \"%@\"",s1,s2
end if
select ( s1 )
case s2
printf @"\"%@\" is equal to \"%@\"",s1,s2
case else
printf @"\"%@\" is not equal to \"%@\"",s1,s2
end select
print @"\n• not equal - case sensitive •"
s2 = @"bravo"
if ( fn StringIsEqual( s1, s2 ) == NO )
printf @"\"%@\" is not equal to \"%@\"",s1,s2
end if
result = fn StringCompare( s1, s2 )
if ( result != NSOrderedSame )
printf @"\"%@\" is not equal to \"%@\"",s1,s2
end if
select ( s1 )
case s2
printf @"\"%@\" is equal to \"%@\"",s1,s2
case else
printf @"\"%@\" is not equal to \"%@\"",s1,s2
end select
print @"\n• ordered before - case sensitive •"
result = fn StringCompare( s1, s2 )
if ( result == NSOrderedAscending )
printf @"\"%@\" is ordered before \"%@\"",s1,s2
end if
print @"\n• ordered after - case sensitive •"
result = fn StringCompare( s2, s1 )
if ( result == NSOrderedDescending )
printf @"\"%@\" is ordered after \"%@\"",s2,s1
end if
print @"\n• equal - case insensitive •"
s2 = @"AlPhA"
result = fn StringCaseInsensitiveCompare( s1, s2 )
if ( result == NSOrderedSame )
printf @"\"%@\" is equal to \"%@\"",s1,s2
end if
result = fn StringCompareWithOptions( s1, s2, NSCaseInsensitiveSearch )
if ( result == NSOrderedSame )
printf @"\"%@\" is equal to \"%@\"",s1,s2
end if
if ( fn StringIsEqual( lcase(s1), lcase(s2) ) )
printf @"\"%@\" is equal to \"%@\"",s1,s2
end if
end fn
 
fn StringComparison
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
• equal - case sensitive •
"alpha" is equal to "alpha"
"alpha" is equal to "alpha"
"alpha" is equal to "alpha"
 
• not equal - case sensitive •
"alpha" is not equal to "bravo"
"alpha" is not equal to "bravo"
"alpha" is not equal to "bravo"
 
• ordered before - case sensitive •
"alpha" is ordered before "bravo"
 
• ordered after - case sensitive •
"bravo" is ordered after "alpha"
 
• equal - case insensitive •
"alpha" is equal to "AlPhA"
"alpha" is equal to "AlPhA"
"alpha" is equal to "AlPhA"
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,671 ⟶ 2,473:
// for Unicode normalization, collation tables, and locale sensitive
// comparisons.
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,683 ⟶ 2,485:
=={{header|Harbour}}==
We will compare two strings, ''s1'' and ''s2''. The following comparisons are case sensitive.
<langsyntaxhighlight lang="visualfoxpro">IF s1 == s2
? "The strings are equal"
ENDIF
Line 1,694 ⟶ 2,496:
IF s1 < s2
? "s2 is lexically ordered after than s1"
ENDIF</langsyntaxhighlight>
To achieve case insensitive comparisons, we should use Upper() or Lower() functions:
<langsyntaxhighlight lang="visualfoxpro">IF Upper( s1 ) == Upper( s2 )
? "The strings are equal"
ENDIF</langsyntaxhighlight>
 
=={{header|Haskell}}==
Examples from the Haskell shell:
<langsyntaxhighlight lang="haskell">
> "abc" == "abc"
True
Line 1,718 ⟶ 2,520:
> map toLower "HELLOWORLD" == map toLower "HelloWorld"
True
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,724 ⟶ 2,526:
Same in both languages.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
s1 := A[1] | "a"
s2 := A[2] | "b"
Line 1,737 ⟶ 2,539:
"123" >> 12 # Lexical comparison (12 coerced into "12")
"123" > 12 # Numeric comparison ("123" coerced into 123)
end</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
The primitive <code>-:</code> can be used to determine whether two strings are equivalent, but J doesn't have other inbuilt lexical comparison operators. They can defined as follows:
<langsyntaxhighlight lang="j">eq=: -: NB. equal
ne=: -.@-: NB. not equal
gt=: {.@/:@,&boxopen *. ne NB. lexically greater than
lt=: -.@{.@/:@,&boxopen *. ne NB. lexically less than
ge=: {.@/:@,&boxopen +. eq NB. lexically greater than or equal to
le=: -.@{.@/:@,&boxopen NB. lexically less than or equal to</langsyntaxhighlight>
 
Note that <code>boxopen</code> is used here so that these operations do not distinguish between the types <i>sequence of characters</i> and <i>boxed sequence of characters</i>. If distinguishing between these types would be desirable, <code>boxopen</code> should be replaced with <code>></code> or a separate test should also be used, such as <code>-:&datatype</code>.
 
'''Usage:'''
<langsyntaxhighlight lang="j"> 'ball' (eq , ne , gt , lt , ge , le) 'bell'
0 1 0 1 0 1
'ball' (eq , ne , gt , lt , ge , le) 'ball'
1 0 0 0 1 1
'YUP' (eq , ne , gt , lt , ge , le) 'YEP'
0 1 1 0 1 0</langsyntaxhighlight>
 
=={{header|Java}}==
A String object in Java represents a UTF-16 string.
Comparisons are done using the equals(), equalsIgnoreCase(), compareTo(), and compareToIgnoreCase() methods.
<langsyntaxhighlight lang="java">public class Compare
{
public static void main (String[] args)
Line 1,797 ⟶ 2,601:
System.out.printf("The case-insensitive lexical relationship is: %d\n\n", A.compareToIgnoreCase(B));
}
}</langsyntaxhighlight>
{{Out}}
<pre>'Hello' and 'Hello' are lexically equal.
Line 1,833 ⟶ 2,637:
The lexical relationship is: -1
The case-insensitive lexical relationship is: 0</pre>
 
=={{header|JavaScript}}==
 
<syntaxhighlight lang="javascript">/*
== equal value
=== equal value and equal type
!= not equal value
!== not equal value or not equal type
< lexically ordered before
> lexically ordered after
*/
 
console.log(
"abcd" == "abcd", // true
"abcd" === "abcd", // true
123 == "123", // true
123 === "123", // false
"ABCD" == "abcd", // false
"ABCD" != "abcd", // true
123 != "123", // false
123 !== "123", // true
"abcd" < "dcba", // true
"abcd" > "dcba", // false
"ABCD".toLowerCase() == "abcd".toLowerCase(), // true (case insensitive)
)</syntaxhighlight>
 
=={{header|jq}}==
jq strings are JSON strings. The jq comparison operators (==, !=, <, <=, >=, >) can be used to compare strings or indeed any JSON entities. Similarly, jq's <tt>sort</tt> and <tt>unique</tt> filters can be used to sort strings. The ordering of strings is determined by the Unicode codepoints.
 
<langsyntaxhighlight lang="jq"># Comparing two strings for exact equality:
"this" == "this" # true
"this" == "This" # false
Line 1,847 ⟶ 2,676:
"beta" < "alpha" # false
 
# > is the inverse of < </langsyntaxhighlight>
jq provides `ascii_downcase` and `ascii_upcase` for ASCII case conversion.
Currently, jq does not have any "toupper" or "tolower" case conversion, but it is easy to define jq equivalents of ruby's downcase and upcase:<lang jq>
# Only characters A to Z are affected
def downcase:
explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;
 
# Only characters a to z are affected
def upcase:
explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;</lang>
With the caveat that these are what they are, case-insensitive comparisons can be achieved as illustrated by this example:
<langsyntaxhighlight lang="jq">("AtoZ" | upcaseascii_upcase) == ("atoz" | upcaseascii_upcase) # true</langsyntaxhighlight>
Numeric strings are treated as any other JSON strings.
 
jq has an extensive library of built-in functions for handling strings. The most recent versions of jq (since 1.4) also have extensive support for PCRE regular expressions (regex), including named captures. Pleaseand seean [http://stedolan.github.io/jq/manual/#Builtinoperatorsandfunctions|jqoption Builtinto Operatorsturn andcase-sensitivity Functions]off. for details.
Please see [http://stedolan.github.io/jq/manual/#Builtinoperatorsandfunctions|jq Builtin Operators and Functions] for details.
 
=={{header|Julia}}==
Line 1,868 ⟶ 2,690:
* Julia can handle both ASCII and non-ASCII chars;
{{trans|Python}}
<langsyntaxhighlight lang="julia">function compare(a, b)
println("\n$a is of type $(typeof(a)) and $b is of type $(typeof(b))")
if a < b println("$a is strictly less than $b") end
Line 1,884 ⟶ 2,706:
compare("24", "123")
compare(24, 123)
compare(5.0, 5)</langsyntaxhighlight>
 
{{out}}
Line 1,918 ⟶ 2,740:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 1,933 ⟶ 2,755:
println("kotlin comes before Kotlin = ${k1 < k2.toLowerCase()}")
println("kotlin comes after Kotlin = ${k1 > k2.toLowerCase()}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,953 ⟶ 2,775:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">// Comparing two strings for exact equality
"'this' == 'this': " + ('this' == 'this') // true
"'this' == 'This': " + ('this' == 'This') // true, as it's case insensitive
Line 1,988 ⟶ 2,810:
"'The quick brown fox jumps over the rhino'->endswith('rhino'): " +
('The quick brown fox jumps over the rhino'->endswith('rhino')) // true
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,017 ⟶ 2,839:
=={{header|Lingo}}==
Lingo's built-in string comparison is case-insensitive:
<langsyntaxhighlight lang="lingo">put "abc"="ABC"
-- 1
 
Line 2,027 ⟶ 2,849:
 
put "abc">"def"
-- 0</langsyntaxhighlight>
 
Case-sensitive string comparison could be implemented e.g. like this:
<langsyntaxhighlight lang="lingo">-- Returns -1 if str1 is less than str2
-- Returns 1 if str1 is greater than str2
-- Returns 0 if str1 and str2 are equal
Line 2,039 ⟶ 2,861:
else if h1>h2 then return 1
return 0
end</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 2,046 ⟶ 2,868:
* Case-insensitivity can be accomplished by using <code>string.upper</code> or <code>string.lower</code> on both strings prior to comparing them.
* Lua does not have a dedicated identity operator as == already plays that role. If two strings have equal contents, they are the same object and therefore equal.
<langsyntaxhighlight lang="lua">function compare(a, b)
print(("%s is of type %s and %s is of type %s"):format(
a, type(a),
Line 2,064 ⟶ 2,886:
compare('24', '123')
compare(24, 123)
compare(5.0, 5)</langsyntaxhighlight>
 
{{out}}
Line 2,094 ⟶ 2,916:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">compare[x_, y_] := Module[{},
If[x == y,
Print["Comparing for equality (case sensitive): " <> x <> " and " <> y <> " ARE equal"],
Line 2,113 ⟶ 2,935:
compare["Hello", "Hello"]
compare["3.1", "3.14159"]
compare["mathematica", "Mathematica"]</langsyntaxhighlight>
{{out}}
<pre>Comparing for equality (case sensitive): Hello and Hello ARE equal
Line 2,129 ⟶ 2,951:
Comparing for order (case sensitive): mathematica comes before Mathematica
Comparing for equality (case insensitive): mathematica and Mathematica ARE equal</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
a="BALL";
b="BELL";
if a==b, disp('The strings are equal'); end;
if strcmp(a,b), disp('The strings are equal'); end;
if a~=b, disp('The strings are not equal'); end;
if ~strcmp(a,b), disp('The strings are not equal'); end;
if a > b, disp('The first string is lexically after than the second'); end;
if a < b, disp('The first string is lexically before than the second'); end;
if a >= b, disp('The first string is not lexically before than the second'); end;
if a <= b, disp('The first string is not lexically after than the second'); end;
% to make a case insensitive comparison convert both strings to the same lettercase:
a="BALL";
b="ball";
if strcmpi(a,b), disp('The first and second string are the same disregarding letter case'); end;
if lower(a)==lower(b), disp('The first and second string are the same disregarding letter case'); end;
 
</syntaxhighlight>
 
{{out}}
<pre>
The strings are not equal
The strings are not equal
The first string is lexically before than the second
The first string is not lexically after than the second
The first and second string are the same disregarding letter case
The first and second string are the same disregarding letter case
</pre>
 
 
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">string1 = input("Please enter a string.")
string2 = input("Please enter a second string.")
 
Line 2,179 ⟶ 3,035:
if string1.lower != string2.lower then
print "Strings are NOT equal. (case insensitive)"
end if</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
While many comparisons in Nanoquery yield the same results as Python, numeric strings are coerced into numeric types, so comparison between numeric strings yields the same results as the equivalent numeric types.
<langsyntaxhighlight Nanoquerylang="nanoquery">def compare(a, b)
println format("\n%s is of type %s and %s is of type %s", a, type(a), b, type(b))
if a < b
Line 2,210 ⟶ 3,066:
compare("24", "123")
compare(24, 123)
compare(5.0, 5)</langsyntaxhighlight>
 
{{out}}
Line 2,253 ⟶ 3,109:
 
 
<langsyntaxhighlight NetRexxlang="netrexx">animal = 'dog'
if animal = 'cat' then
say animal "is lexically equal to cat"
Line 2,276 ⟶ 3,132:
if ' cat ' == 'cat' then
say "this will not print because comparison is strict"
</syntaxhighlight>
</lang>
The list of strict comparison operators described in the [[#REXX|REXX]] sample apply to [[NetRexx]] too.
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strutils
 
var s1: string = "The quick brown"
Line 2,291 ⟶ 3,147:
echo(">= : ", s1 >= s2)
# cmpIgnoreCase(a, b) => 0 if a == b; < 0 if a < b; > 0 if a > b
echo("cmpIgnoreCase :", s1.cmpIgnoreCase s2)</langsyntaxhighlight>
{{out}}
<pre>== : false
Line 2,303 ⟶ 3,159:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">"abcd" "abcd" ==
"abcd" "abce" <>
"abcd" "abceed" <=
"abce" "abcd" >
"abcEEE" toUpper "ABCeee" toUpper ==</langsyntaxhighlight>
 
=={{header|ooRexx}}==
Line 2,313 ⟶ 3,169:
 
There is a way to "caseless" compare array elements:
<syntaxhighlight lang="text">a=.array~of('A 1','B 2','a 3','b 3','A 5')
a~sortwith(.caselesscomparator~new)
Do i=1 To 5
Say a[i]
End</langsyntaxhighlight>
Output:
<pre>A 1
Line 2,332 ⟶ 3,188:
Scalar variables are weakly typed in Perl, and there are two sets of comparison operators that can be used on them: One set for (coercive) numeric comparison, and one set for (coercive) lexical string comparison. The second set is demonstrated in the following:
 
<langsyntaxhighlight lang="perl">use v5.16; # ...for fc(), which does proper Unicode casefolding.
# With older Perl versions you can use lc() as a poor-man's substitute.
 
Line 2,356 ⟶ 3,212:
compare('Hello', 'Hello');
compare('5', '5.0');
compare('perl', 'Perl');</langsyntaxhighlight>
 
{{out}}
Line 2,380 ⟶ 3,236:
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang Phix>if name=="pete" then ?"The strings are equal" end if
<!--<syntaxhighlight lang="phix">(phixonline)-->
if name!="pete" then ?"The strings are not equal" end if
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
if name<"pete" then ?"name is lexically first" end if
<span style="color: #004080;">string</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"Pete"</span>
if name>"pete" then ?"name is lexically last" end if
<span style="color: #008080;">if</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">==</span><span style="color: #008000;">"pete"</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"The strings are equal"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if upper(name)=upper("pete") then ?"case insensitive match" end if
<span style="color: #008080;">if</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">"pete"</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"The strings are not equal"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if match("pete",lower(name)) then ?"petes in there somewhere" end if</lang>
<span style="color: #008080;">if</span> <span style="color: #000000;">name</span><span style="color: #0000FF;"><</span><span style="color: #008000;">"pete"</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"name is lexically first"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">></span><span style="color: #008000;">"pete"</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"name is lexically last"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">name</span><span style="color: #0000FF;">)=</span><span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"pete"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"case insensitive match"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"pete"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">name</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"petes in there somewhere"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
"The strings are not equal"
"name is lexically first"
"case insensitive match"
"petes in there somewhere"
</pre>
 
=={{header|Phixmonti}}==
{{trans|Phix}}
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/String_comparison
by Galileo, 11/2022 #/
 
include ..\Utilitys.pmt
 
"Pete" >ps
 
"pete" tps == if "The strings are equal" ? endif
"pete" tps != if "The strings are not equal" ? endif
tps "pete" < if ( tps " is lexically first" ) lprint nl endif
tps "pete" > if ( tps " is lexically last" ) lprint nl endif
tps upper "pete" upper == if "case insensitive match" ? endif
ps> lower "pete" find if "petes in there somewhere" ? endif
</syntaxhighlight>
{{out}}
<pre>The strings are not equal
Pete is lexically first
case insensitive match
petes in there somewhere
 
=== Press any key to exit ===</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
S1 = "abc",
S2 = "def",
S1 == S2, % -> false.
S1 != S2, % -> true.
S1 @< S2, % -> true. Is S1 lexicographically less than S1?
S1 @> S2, % -> false.
to_lowercase(S1) == to_lowercase(S2), % -> false.
"1234" @> "123", % -> true. lexical comparison
"1234" @< 12342222, % -> false. No coersion is done. Numbers are always ordered before strings
 
123 < 1234. % -> true '<' is used only for numbers</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq
str= =
str< <
Line 2,405 ⟶ 3,312:
(str< "12" "45") )
(bye)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
"a" -lt "b" # lower than
"a" -eq "b" # equal
Line 2,415 ⟶ 3,322:
"a" -ne "b" # not equal
"a" -ge "b" # greater than or equal
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,427 ⟶ 3,334:
By default operators are case insensitive.
Preceed them by the letter "c" to make them case sensitive like this:
<syntaxhighlight lang="powershell">
<lang PowerShell>
"a" -eq "A"
"a" -ceq "A"
</syntaxhighlight>
</lang>
<pre>
True
Line 2,437 ⟶ 3,344:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Macro StrTest(Check,tof)
Print("Test "+Check+#TAB$)
If tof=1 : PrintN("true") : Else : PrintN("false") : EndIf
Line 2,473 ⟶ 3,380:
Compare(a$,b$,1,1)
Input()
EndIf</langsyntaxhighlight>
{{out}}
<pre>
Line 2,515 ⟶ 3,422:
* Python is strongly typed. The string '24' is never coerced to a number, (or vice versa).
* Python does not have case-insensitive string comparison operators, instead use <code>name.upper()</code> or <code>name.lower()</code> to coerce strings to the same case and compare the results.
<langsyntaxhighlight lang="python">def compare(a, b):
print("\n%r is of type %r and %r is of type %r"
% (a, type(a), b, type(b)))
Line 2,531 ⟶ 3,438:
compare('24', '123')
compare(24, 123)
compare(5.0, 5)</langsyntaxhighlight>
 
{{out}}
Line 2,563 ⟶ 3,470:
5.0 is equal to 5
5.0 has negated object identity with 5</pre>
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
 
Dim As String String1, String2
 
' direct string comparison using case sensitive
String1 = "GWbasic"
String2 = "QuickBasic"
If String1 = String2 Then Print String1; " is equal to "; String2 Else Print String1; " is NOT egual to "; String2
String1 = "gWbasic"
String2 = "GWBasic"
If String1 = String2 Then Print String1; " is equal to "; String2 Else Print String1; " is NOT egual to "; String2
 
' direct string comparison using case insensitive
If UCase$(String1) = UCase$(String2) Then Print String1; " is equal to "; String2; Else Print String1; " is NOT egual to "; String2;
Print " case insensitive"
String1 = "GwBasiC"
String2 = "GWBasic"
If LCase$(String1) = LCase$(String2) Then Print String1; " is equal to "; String2; Else Print String1; " is NOT egual to "; String2;
Print " case insensitive"
 
' lexical order
String1 = "AAAbbb"
String2 = "AaAbbb"
If String1 > String2 Then Print String1; " is after "; String2 Else Print String1; " is before "; String2
 
' number in string format comparison
String1 = "0123"
String2 = "5"
' lexical order
If String1 > String2 Then Print String1; " is after "; String2 Else Print String1; " is before "; String2
' value order
If Val(String1) > Val(String2) Then Print String1; " is bigger than "; String2 Else Print String1; " is lower "; String2
 
Print "QB64, like QBasic, has native coercive/allomorphic operators for string type variable"
End
</syntaxhighlight>
 
=={{header|Quackery}}==
 
As a dialogue in the Quackery shell.
 
<pre>/O> ( compare two strings for equality )
... $ "abc" $ "xyz" =
... echo ( 0 = false, 1 = true )
...
0
Stack empty.
 
/O> ( compare two strings for inequality )
... $ "abc" $ "xyz" !=
... echo ( 0 = false, 1 = true )
...
1
Stack empty.
 
//O> ( compare two strings to see if one is lexically ordered before the other )
... $ "abc" $ "xyz" $<
... echo ( 0 = false, 1 = true )
...
1
Stack empty.
 
/O> ( compare two strings to see if one is lexically ordered after the other )
... $ "abc" $ "xyz" $>
... echo ( 0 = false, 1 = true )
...
1
Stack empty.
 
/O> ( for case insensitive, convert both strings to the same case )
... [ $ "" swap witheach [ upper join ] ] is upper$ ( $ --> $ )
... $ "AbC" upper$ $ "aBc" upper$ =
... echo ( 0 = false, 1 = true )
...
1
Stack empty.
 
/O> ( Numeric strings are not treated differently to other strings. )
... ( Lexical ordering uses QACSFOT rather than ASCII/Unicode ordering. )
( )
... ( "Quackery Arbitrary Character Sequence For Ordered Text" )
... ( 0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrS )
... ( sTtUuVvWwXxYyZz()[]{}<>~=+-*/^\|_.,:;?!'"`%@&#$ )
...
 
Stack empty.</pre>
 
=={{header|R}}==
{{trans|Python}}
<langsyntaxhighlight lang="rsplus">compare <- function(a, b)
{
cat(paste(a, "is of type", class(a), "and", b, "is of type", class(b), "\n"))
Line 2,584 ⟶ 3,578:
compare('24', '123')
compare(24, 123)
compare(5.0, 5)</langsyntaxhighlight>
 
{{out}}
Line 2,614 ⟶ 3,608:
 
And a more ridiculous version:
<langsyntaxhighlight lang="rsplus">compare <- function(a, b)
{
cat(paste(a, "is of type", class(a), "and", b, "is of type", class(b), "\n"))
Line 2,633 ⟶ 3,627:
invisible()
}</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,654 ⟶ 3,648:
;; How to achieve both case sensitive comparisons and case insensitive comparisons within the language
(string-ci=? "foo" "FOO")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,662 ⟶ 3,656:
 
String comparisons never do case folding because that's a very complicated subject in the modern world of Unicode. (You can explicitly apply an appropriate case-folding function to the arguments before doing the comparison, or for "equality" testing you can do matching with a case-insensitive regex, assuming Unicode's language-neutral case-folding rules are okay.)
<syntaxhighlight lang="raku" perl6line>sub compare($a,$b) {
my $A = "{$a.WHAT.^name} '$a'";
my $B = "{$b.WHAT.^name} '$b'";
Line 2,697 ⟶ 3,691:
compare 24, 123;
compare 5.1, 5;
compare 5.1e0, 5 + 1/10;</langsyntaxhighlight>
{{out}}
<pre>Str 'YUP' and Str 'YUP' are lexically equal
Line 2,748 ⟶ 3,742:
The generic relationship of Num '5.1' and Rat '5.1' is Same
The numeric relationship of Num '5.1' and Rat '5.1' is Same</pre>
 
=== Unicode normalization by default ===
 
Be aware that Raku applies normalization (Unicode NFC form (Normalization Form Canonical)) by default to all input and output except for file names [https://docs.raku.org/language/unicode See docs]. Raku follows the Unicode spec. Raku follows '''all''' of the Unicode spec, including parts that some people don't like. There are some graphemes for which the Unicode consortium has specified that the NFC form is a different (though usually visually identical) grapheme. Referred to in [https://www.unicode.org/reports/tr15 Unicode standard annex #15] as '''Canonical Equivalence'''. Raku adheres to that spec.
 
One that people seem to get hung up on is the Kelvin symbol "K" getting automatically converted to ASCII uppercase "K".
 
<syntaxhighlight lang="raku" line>say "\c[KELVIN SIGN]".uniname;
# => LATIN CAPITAL LETTER K
 
my $kelvin = "\c[KELVIN SIGN]";
my $k = "\c[LATIN CAPITAL LETTER K]";
say ($kelvin eq $k); # True, lexically equal
say ($kelvin eqv $k); # True, generically equal
say ($kelvin === $k); # True, identical objects</syntaxhighlight>
 
In most programming language the previous two objects wouldn't be equivalent, but since Raku follows the Unicode specification, and normalization is applied automatically, they show up as equivalent.
 
It's officially identified as a possible trap for string handling. [https://docs.raku.org/language/traps#All_text_is_normalized_by_default See docs].
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
set a = "Hello"
set b = "World"
if a == b
' a is equal to b (case sensitive)
end if
if lower(a) == lower(b)
' a is equal to b (case insensitive)
end if
if a !== b
' a is not equal to b (case sensitive)
end if
if lower(a) !== lower(b)
' a is not equal to b (case insensitive)
end if
if a << b
' a is lexically first to b (case sensitive)
end if
if lower(a) << lower(b)
' a is lexically first to b (case insensitive)
end if
if a >> b
' a is lexically after b (case sensitive)
end if
if lower(a) >> Lower(b)
' a is lexically after b (case insensitive)
end if
</syntaxhighlight>
Variables in Relation are not typed. They are treated as numbers of string depending on the operator. Numbers are always treated as strings, if you use the operators '''==''', '''!==''', '''<<''' and '''>>'''
 
=={{header|REXX}}==
Line 2,766 ⟶ 3,810:
Note that some REXXes can use (support) characters other than a backslash &nbsp; ['''\'''] &nbsp; for a logical not &nbsp; ['''¬'''].
<br>Still other REXX support the use of a tilde &nbsp; ['''~'''] &nbsp; for a logical not.
<langsyntaxhighlight lang="rexx">/*REXX program shows different ways to compare two character strings.*/
say 'This is an ' word('ASCII EBCDIC', 1+(1=='f1')) ' system.'
say
Line 2,803 ⟶ 3,847:
caselessComp: procedure; arg a,b /*ARG uppercases the A & B args.*/
return a==b /*if exactly equal, return 1. */
</syntaxhighlight>
</lang>
Programming note:
 
Line 2,827 ⟶ 3,871:
(a) if both operands are NUMBERS (normal, non-strict) comparisons will always be done arithmetically.
<br>(b) to implement caseless comparison one can proceed as follows:
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 16.05.2013 Walter Pachl
**********************************************************************/
Line 2,849 ⟶ 3,893:
Return res
 
q: Return '"'arg(1)'"'</langsyntaxhighlight>
Output:
<pre>"A" < "a" -> 0
Line 2,857 ⟶ 3,901:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
 
if s1 = s2
Line 2,878 ⟶ 3,922:
ok
 
</syntaxhighlight>
</lang>
 
=={{header|Robotic}}==
Line 2,887 ⟶ 3,931:
There is no opposite of the case-sensitive comparison.
 
<langsyntaxhighlight lang="robotic">
set "$str1" to "annoy"
set "$str2" to "annoy"
Line 2,917 ⟶ 3,961:
* "&$str1& is lexicographically less than &$str2&"
end
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
Equality can be tested either with <code>==</code> or <code>SAME</code> operators:
"ab" "abc" ==
returns 0 (false).
 
To test inequality:
"ab" "abc" ≠
returns 1 (true).
 
Lexical order can be checked with <code><</code>, <code>≤</code>, <code>></code> or <code> ≥</code> operators.
"ab" "abc" ≤
returns also 1 (true).
All the above tests are case-sensitive.
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">method_names = [:==,:!=, :>, :>=, :<, :<=, :<=>, :casecmp]
[["YUP", "YUP"], ["YUP", "Yup"], ["bot","bat"], ["aaa", "zz"]].each do |str1, str2|
method_names.each{|m| puts "%s %s %s\t%s" % [str1, m, str2, str1.send(m, str2)]}
puts
end</langsyntaxhighlight>
{{output}}
<pre>
Line 2,966 ⟶ 4,023:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a$ = "dog"
b$ = "cat"
if a$ = b$ then print "the strings are equal" ' test for equalitY
Line 2,974 ⟶ 4,031:
if a$ <= b$ then print a$;" is not lexicallY higher than ";b$
if a$ >= b$ then print a$;" is not lexicallY lower than ";b$
end</langsyntaxhighlight>
 
=={{header|Rust}}==
Comparisons are case sensitive by default, all (Ascii) uppercase letters are treated as lexically before all lowercase letters.
For case-insensitive comparisons, use Ascii Extensions. In general, case is not a concept that applies to all unicode symbols.
<langsyntaxhighlight lang="rust">use std::ascii::AsciiExt; // for case insensitives only
 
fn main() {
Line 3,007 ⟶ 4,064:
 
// repeat checks
}</langsyntaxhighlight>
 
{{out}}
Line 3,015 ⟶ 4,072:
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala">object Compare extends App {
def compare(a: String, b: String) {
if (a == b) println(s"'$a' and '$b' are lexically equal.")
Line 3,038 ⟶ 4,095:
compare("ĴÃVÁ", "ĴÃVÁ")
compare("ĴÃVÁ", "ĵãvá")
}</langsyntaxhighlight>
{{out}}
<pre>'Hello' and 'Hello' are lexically equal.
Line 3,076 ⟶ 4,133:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">
;; Comparing two strings for exact equality
(string=? "hello" "hello")
Line 3,090 ⟶ 4,147:
;; case insensitive comparison
(string-ci=? "hello" "Hello")</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 3,104 ⟶ 4,161:
[http://seed7.sourceforge.net/libraries/string.htm#lower%28in_string%29 lower] can be used to do an insensitive comparison.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: showComparisons (in string: a, in string: b) is func
Line 3,128 ⟶ 4,185:
showComparisons("the", "there");
showComparisons("there", "the");
end func;</langsyntaxhighlight>
 
The function below compares strings, which may contain digit sequences. The digit sequences are compared numerically.
 
<langsyntaxhighlight lang="seed7">include "scanstri.s7i";
 
const func integer: cmpNumeric (in var string: stri1, in var string: stri2) is func
Line 3,166 ⟶ 4,223:
end if;
end while;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/string.htm#cmpNumeric]
Line 3,172 ⟶ 4,229:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">var methods = %w(== != > >= < <= <=>)
for s1, s2 in [<YUP YUP>,<YUP Yup>,<bot bat>,<aaa zz>] {
methods.each{|m| "%s %s %s\t%s\n".printf(s1, m, s2, s1.(m)(s2))}
print "\n"
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{trans|Ruby}}
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">methods := #(= ~= > >= < <= sameAs: ).
#(
('YUP' 'YUP')
('YUP' 'yup')
) pairsDo:[:s1 :s2 |
methods do:[:m |
'%-20s\t%s\n' printf:
{
('(%S %s %S)' printf:{s1 . m . s2}) .
(s1 perform:m with:s2)
} on:Stdout
].
Stdout cr
]</syntaxhighlight>
{{out}}
<pre>('YUP' = 'YUP') true
('YUP' ~= 'YUP') false
('YUP' > 'YUP') false
('YUP' >= 'YUP') true
('YUP' < 'YUP') false
('YUP' <= 'YUP') true
('YUP' sameAs: 'YUP') true
 
('YUP' = 'yup') false
('YUP' ~= 'yup') true
('YUP' > 'yup') false
('YUP' >= 'yup') false
('YUP' < 'yup') true
('YUP' <= 'yup') true
('YUP' sameAs: 'yup') true</pre>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4"> s1 = 'mnopqrs'
s2 = 'mnopqrs'
s3 = 'mnopqr'
Line 3,213 ⟶ 4,304:
OUTPUT = GT('1234', 1233) '"1234" is greater than 1233 (numeric comparison).'
OUTPUT = LT('1233', 1234) '"1233" is less than 1234 (numeric comparison).'
END</langsyntaxhighlight>
{{out}}
<pre>
Line 3,241 ⟶ 4,332:
 
=={{header|Standard ML}}==
<syntaxhighlight lang="text">map String.compare [ ("one","one"),
("one","two"),
("one","Two"),
Line 3,251 ⟶ 4,342:
"one" <> "two" ;
val it = true: bool
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func compare (a: String, b: String) {
if a == b {
println("'\(a)' and '\(b)' are lexically equal.")
Line 3,276 ⟶ 4,367:
}
}
compare("cat", "dog")</langsyntaxhighlight>
{{Out}}
<pre>
Line 3,283 ⟶ 4,374:
'cat' is not lexically after 'dog'.
</pre>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
$a -> \(when <=$b> do '$a; equals $b;' ! \) -> !OUT::write
 
$a -> \(when <~=$b> do '$a; not equal to $b;' ! \) -> !OUT::write
 
$a -> \(when <..$b> do '$a; lexically less or equal to $b;' ! \) -> !OUT::write
 
$a -> \(when <$b..> do '$a; lexically greater or equal to $b;' ! \) -> !OUT::write
 
$a -> \(when <..~$b> do '$a; lexically less than $b;' ! \) -> !OUT::write
 
$a -> \(when <$b~..> do '$a; lexically greater than $b;' ! \) -> !OUT::write
 
$a -> \(when <'$b;'> do '$a; matches the regex $b;' ! \) -> !OUT::write
 
$a -> \(when <'(?i)$b;'> do '$a; matches the regex $b; case insensitively' ! \) -> !OUT::write
</syntaxhighlight>
 
=={{header|Tcl}}==
The best way to compare two strings in Tcl for equality is with the <code>eq</code> and <code>ne</code> expression operators:
<langsyntaxhighlight lang="tcl">if {$a eq $b} {
puts "the strings are equal"
}
if {$a ne $b} {
puts "the strings are not equal"
}</langsyntaxhighlight>
The numeric <code>==</code> and <code>!=</code> operators also mostly work, but can give somewhat unexpected results when the both the values ''look'' numeric. The <code>string equal</code> command is equally suited to equality-testing (and generates the same bytecode).
 
For ordering, the <code>&lt;</code> and <code>&gt;</code> operators may be used, but again they are principally numeric operators. For guaranteed string ordering, the result of the <code>string compare</code> command should be used instead (which uses the unicode codepoints of the string):
<langsyntaxhighlight lang="tcl">if {[string compare $a $b] < 0} {
puts "first string lower than second"
}
if {[string compare $a $b] > 0} {
puts "first string higher than second"
}</langsyntaxhighlight>
Greater-or-equal and less-or-equal operations can be done by changing what exact comparison is used on the result of the <code>string compare</code>.
 
Tcl also can do a prefix-equal (approximately the same as <code>strncmp()</code> in [[C]]) through the use of the <tt>-length</tt> option:
<langsyntaxhighlight lang="tcl">if {[string equal -length 3 $x "abc123"]} {
puts "first three characters are equal"
}</langsyntaxhighlight>
And case-insensitive equality is (orthogonally) enabled through the <tt>-nocase</tt> option. These options are supported by both <code>string equal</code> and <code>string compare</code>, but not by the expression operators.
 
Line 3,312 ⟶ 4,422:
Traditional bourne shell (which used the 'test' command for comparisons) had no way of doing lexical comparisons.
 
<langsyntaxhighlight lang="sh">#!/bin/sh
 
A=Bell
Line 3,329 ⟶ 4,439:
# 0 , -0 , 0.0 and 00 are all lexically different if tested using the above methods.
 
# However this may not be the case if other tools, such as awk are the slave instead of test.</langsyntaxhighlight>
 
Bash and other POSIX shells do support lexical comparisons:
 
<langsyntaxhighlight lang="bash">
#!/bin/bash
 
Line 3,373 ⟶ 4,483:
compare 24 123
compare 50 20
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,398 ⟶ 4,508:
=={{header|Vala}}==
{{trans|Nim}}
<langsyntaxhighlight lang="vala">void main() {
var s1 = "The quick brown";
var s2 = "The Quick Brown";
Line 3,407 ⟶ 4,517:
stdout.printf("> : %s\n", s1 > s2 ? "true" : "false");
stdout.printf(">= : %s\n", s1 >= s2 ? "true" : "false");
}</langsyntaxhighlight>
 
{{out}}
Line 3,417 ⟶ 4,527:
> : true
>= : true
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="go">fn main() {
c := "cat"
d := "dog"
if c == d {
println('$c is bytewise identical to $d')
}
if c != d {
println('$c is bytewise different from $d')
}
if c > d {
println('$c is lexically bytewise greater than $d')
}
if c < d {
println('$c is lexically bytewise less than $d')
}
if c >= d {
println('$c is lexically bytewise greater than or equal to $d')
}
if c <= d {
println('$c is lexically bytewise less than or equal to $d')
}
}</syntaxhighlight>
{{out}}
<pre>
cat is bytewise different from dog
cat is lexically bytewise less than dog
cat is lexically bytewise less than or equal to dog
</pre>
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">== 'example1' 'example2' -- io.writeln io.stdout; # Test for exact equality.
== 'example1' 'example2' -> ! -- io.writeln io.stdout; # Test for inequality.
< 'example1' 'example2' -- io.writeln io.stdout; # Test for lexical before.
Line 3,430 ⟶ 4,570:
 
# This is false. Strings are not coerced to numbers and vice-versa.
== '3' 3 -- io.writeln io.stdout;</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-str}}
The only string comparisons built into the language itself are equality and inequality. However, the above module enables us to do full lexicographical comparisons of any strings, including numeric strings, by comparing their corresponding Unicode codepoints.
 
Case insensitive comparisons can be achieved by converting both strings to the same case before the comparisons are made.
<syntaxhighlight lang="wren">import "./str" for Str
 
var compareStrings = Fn.new { |a, b, sens|
System.write("Comparing '%(a)' and '%(b)', ")
var c
var d
if (sens) {
System.print("case sensitively:")
c = a
d = b
} else {
System.print("case insensitively:")
c = Str.lower(a)
d = Str.lower(b)
}
System.print(" %(a) < %(b) -> %(Str.lt(c, d))")
System.print(" %(a) > %(b) -> %(Str.gt(c, d))")
System.print(" %(a) == %(b) -> %(c == d)")
System.print(" %(a) != %(b) -> %(c != d)")
System.print(" %(a) <= %(b) -> %(Str.le(c, d))")
System.print(" %(a) >= %(b) -> %(Str.ge(c, d))")
System.print()
}
 
compareStrings.call("cat", "dog", true)
compareStrings.call("Rat", "RAT", true)
compareStrings.call("Rat", "RAT", false)
compareStrings.call("1100", "200", true)</syntaxhighlight>
 
{{out}}
<pre>
Comparing 'cat' and 'dog', case sensitively:
cat < dog -> true
cat > dog -> false
cat == dog -> false
cat != dog -> true
cat <= dog -> true
cat >= dog -> false
 
Comparing 'Rat' and 'RAT', case sensitively:
Rat < RAT -> false
Rat > RAT -> true
Rat == RAT -> false
Rat != RAT -> true
Rat <= RAT -> false
Rat >= RAT -> true
 
Comparing 'Rat' and 'RAT', case insensitively:
Rat < RAT -> false
Rat > RAT -> false
Rat == RAT -> true
Rat != RAT -> false
Rat <= RAT -> true
Rat >= RAT -> true
 
Comparing '1100' and '200', case sensitively:
1100 < 200 -> true
1100 > 200 -> false
1100 == 200 -> false
1100 != 200 -> true
1100 <= 200 -> true
1100 >= 200 -> false
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang="xpl0">include xpllib; \provides StrLen, ToLower, StrCopy, and StrCmp
 
proc StrToLower(A, B);
char A, B, I;
for I:= 0 to StrLen(B) do A(I):= ToLower(B(I));
 
proc CompareStrings(A, B, Sens);
char A, B, Sens, C, D;
[C:= Reserve(StrLen(A)+1);
D:= Reserve(StrLen(B)+1);
Text(0, "Comparing "); Text(0, A); Text(0, " and "); Text(0, B); Text(0, ", ");
if Sens then
[Text(0, "case sensitively:^m^j");
StrCopy(C, A);
StrCopy(D, B);
]
else [Text(0, "case insensitively:^m^j");
StrToLower(C, A);
StrToLower(D, B);
];
Text(0, " "); Text(0, A); Text(0, " < "); Text(0, B); Text(0, " -> ");
Text(0, if StrCmp(C, D) < 0 then "true" else "false"); CrLf(0);
Text(0, " "); Text(0, A); Text(0, " > "); Text(0, B); Text(0, " -> ");
Text(0, if StrCmp(C, D) > 0 then "true" else "false"); CrLf(0);
Text(0, " "); Text(0, A); Text(0, " = "); Text(0, B); Text(0, " -> ");
Text(0, if StrCmp(C, D) = 0 then "true" else "false"); CrLf(0);
Text(0, " "); Text(0, A); Text(0, " # "); Text(0, B); Text(0, " -> ");
Text(0, if StrCmp(C, D) # 0 then "true" else "false"); CrLf(0);
Text(0, " "); Text(0, A); Text(0, " <= "); Text(0, B); Text(0, " -> ");
Text(0, if StrCmp(C, D) <= 0 then "true" else "false"); CrLf(0);
Text(0, " "); Text(0, A); Text(0, " >= "); Text(0, B); Text(0, " -> ");
Text(0, if StrCmp(C, D) >= 0 then "true" else "false"); CrLf(0);
CrLf(0);
];
 
[CompareStrings("cat", "dog", true);
CompareStrings("Rat", "RAT", true);
CompareStrings("Rat", "RAT", false);
CompareStrings("1100", "200", true);
]</syntaxhighlight>
 
{{out}}
<pre>
Comparing cat and dog, case sensitively:
cat < dog -> true
cat > dog -> false
cat = dog -> false
cat # dog -> true
cat <= dog -> true
cat >= dog -> false
 
Comparing Rat and RAT, case sensitively:
Rat < RAT -> false
Rat > RAT -> true
Rat = RAT -> false
Rat # RAT -> true
Rat <= RAT -> false
Rat >= RAT -> true
 
Comparing Rat and RAT, case insensitively:
Rat < RAT -> false
Rat > RAT -> false
Rat = RAT -> true
Rat # RAT -> false
Rat <= RAT -> true
Rat >= RAT -> true
 
Comparing 1100 and 200, case sensitively:
1100 < 200 -> true
1100 > 200 -> false
1100 = 200 -> false
1100 # 200 -> true
1100 <= 200 -> true
1100 >= 200 -> false
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">"foo" == "foo" //True
"foo" == "FOO" //False
"foo" == "foobar" //False
Line 3,450 ⟶ 4,737:
123<"123" //False, int on left forces "123".toInt()
123<"1234" //True
2345<"1234" //False</langsyntaxhighlight>
 
 
162

edits