Engee documentation
Notebook

Text Comparison

In this example, let's look at 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 logical array in which 1 (true) is true, and 0 (false) is incorrect.

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 relation operators >, >=, < and <=. Lines starting with uppercase letters precede lines starting with lowercase letters. For example, the string "ABC" is smaller than "abc". Numbers and some punctuation marks are also placed 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 larger 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. 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

In this article, functions for performing text comparison in string arrays were considered. For more information about working with text and string arrays, see the sections: Text strings and Arrays