Книга: Practical Common Lisp

String Comparisons

String Comparisons

You can compare strings using a set of functions that follow the same naming convention as the character comparison functions except with STRING as the prefix rather than CHAR (see Table 10-3).

Table 10-3. String Comparison Functions

Numeric Analog Case-Sensitive Case-Insensitive
= STRING= STRING-EQUAL
/= STRING/= STRING-NOT-EQUAL
< STRING< STRING-LESSP
> STRING> STRING-GREATERP
<= STRING<= STRING-NOT-GREATERP
>= STRING>= STRING-NOT-LESSP

However, unlike the character and number comparators, the string comparators can compare only two strings. That's because they also take keyword arguments that allow you to restrict the comparison to a substring of either or both strings. The arguments—:start1, :end1, :start2, and :end2—specify the starting (inclusive) and ending (exclusive) indices of substrings in the first and second string arguments. Thus, the following:

(string= "foobarbaz" "quuxbarfoo" :start1 3 :end1 6 :start2 4 :end2 7)

compares the substring "bar" in the two arguments and returns true. The :end1 and :end2 arguments can be NIL (or the keyword argument omitted altogether) to indicate that the corresponding substring extends to the end of the string.

The comparators that return true when their arguments differ—that is, all of them except STRING= and STRING-EQUAL—return the index in the first string where the mismatch was detected.

(string/= "lisp" "lissome") ==> 3

If the first string is a prefix of the second, the return value will be the length of the first string, that is, one greater than the largest valid index into the string.

(string< "lisp" "lisper") ==> 4

When comparing substrings, the resulting value is still an index into the string as a whole. For instance, the following compares the substrings "bar" and "baz" but returns 5 because that's the index of the r in the first string:

(string< "foobar" "abaz" :start1 3 :start2 1) ==> 5 ; N.B. not 2

Other string functions allow you to convert the case of strings and trim characters from one or both ends of a string. And, as I mentioned previously, since strings are really a kind of sequence, all the sequence functions I'll discuss in the next chapter can be used with strings. For instance, you can discover the length of a string with the LENGTH function and can get and set individual characters of a string with the generic sequence element accessor function, ELT, or the generic array element accessor function, AREF. Or you can use the string-specific accessor, CHAR. But those functions, and others, are the topic of the next chapter, so let's move on.

Оглавление книги


Генерация: 1.093. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз