Engee documentation
Notebook

Text Comparison

In this example, let's see how to compare text fragments represented as string arrays.

Comparing strings for equality

You can compare arrays of strings for equality using the relational operators == and !=. When you compare arrays of strings, the output is a boolean array with 1 (true) indicating the relationship is true and 0 (false) indicating it is false.

In [ ]:
str1 = "Hello";
str2 = "World";
str1,str2
Out[0]:
("Hello", "World")
In [ ]:
str1 != str2
Out[0]:
true
In [ ]:
str1 = ["Mercury" "Gemini" "Apollo";"Skylab" "Skylab B" "International Space Station"];
str2 = "Apollo";
str1 .== str2
Out[0]:
2×3 BitMatrix:
 0  0  1
 0  0  0
In [ ]:
str2 = ["Mercury" "Mars" "Apollo";"Jupiter" "Saturn" "Neptune"];
str1 .!= str2
Out[0]:
2×3 BitMatrix:
 0  1  0
 1  1  1

Comparing strings with other relation operators

You can also compare strings using the >, >=, <, and <= relation operators. Strings starting with uppercase letters precede strings starting with lowercase letters. For example, the string "ABC" is less than "abc". Numbers and some punctuation marks also come before letters.

In [ ]:
"ABC" < "abc"
Out[0]:
true

Compare an array of strings containing names with another name using the > operator. The names Sanchez, de Ponte, and Nash come after Matthews because S, d, and N are all greater than M.

In [ ]:
str = ["Sanchez","Jones","de Ponte","Crosby","Nash"]; 
TF = (str .> "Matthews")
Out[0]:
5-element BitVector:
 1
 0
 1
 0
 1

There is also a function cmp(), which compares two strings. It returns 0 if they are equal, 1 when the first string argument is greater than the second, and -1 when the first argument is less than the second, respectively.

In [ ]:
cmp("ABC","abc")
Out[0]:
-1

This article has covered functions to perform text comparisons on string arrays. More details about working with text and string arrays can be found in the sections: Text Strings and Arrays