9.6 Advanced String Searching
進階字元串查找
The next group of functions simplify the location and extraction of individual substrings from a string.
接下來的一組函數簡化了從一個字元串中查找和抽取一個子串的過程。
9.6.1 Finding String Prefixes
The strspn and strcspn functions count characters at the beginning of a string. Their prototypes are shown :
strspn 和strcspn 函數用于在字元串的起始位置對字元計數。它們的原型如下所示:
size_t strspn( char const *str, char const *group );
size_t strcspn( char const *str, char const *group );
The group string specifies one or more characters. strspn returns the number of characters at the beginning of str that match any of these characters. For example, if group contained the whitespace characters space, tab, and so forth, this function would return the number of whitespace characters found at the beginning of str. The next character of str would be the first non‐whitespace character.
group 字元串指定一個或多個字元。strspn 傳回str起始部分比對group 中任意字元的字元數。例如,如果group 包含了空格、制表符等空白字元,那麼這個函數将傳回str起始部分空白字元的數目。str 的下一個字元就是它的第1 個非空白字元。
Consider this example:
考慮下面這個例子:
int len1, len2;
char buffer[] = "25,142,330,Smith,J,239-4123";
len1 = strspn( buffer, "0123456789" );
len2 = strspn( buffer, ",0123456789" );
Of course, the buffer would not normally be initialized in this manner; it would contain data read in at run time. But with this value in the buffer, the variable len1 would be set to two, and the variable len2 would be set to 11. The following code will compute a pointer to the first non‐whitespace character in a string.
當然, buffer 緩沖區在正常情況下是不會用這個方法進行初始化的。它将會包含在運作時讀取的資料。但是在buffer 中有了這個值之後,變量len1 将被設定為2 ,變量len2将被設定為11。 下面的代碼将計算一個指向于符串中第1 個非空白字元的指針。
ptr = buffer + strspn( buffer, " \n\r\f\t\v" );
strcspn works similarly except that only characters that are not in group are counted. The c in the name strcspn comes from the notion that the character group is complemented, that is, exchanged for all of the characters it did not originally contain. If you used the string ʺ \n\r\f\t\vʺ for the group argument, this function would return the number of non‐whitespace characters found at the beginning of the first argument.
strcspn 函數和strspn 函數正好相反,它對str 字元串起始部分中不與group 中任何字元比對的字元進行計數。strcspn 這個名字中字母c 來源于對一組字元求補這個概念,也就是把這些字元換成原先并不存在的字元。如果你使用\n\r\f\t\v作為group 參數,這個函數将傳回第1 個參數字元串起始部分所有非空白字元的值。
上一章 Pointers on C——9 Strings, Characters, and Bytes.6