.注重:你應該去了解一下"string-n”函數,雖然它們使用起來有些困難,但用它們編寫的程序兼容性更好,錯誤更少。 假如你愿意的話,可以用函數strcpy()和strcat()重新編寫例12.5a中的程序,并用很長的足以溢出緩沖區的參數運行它。會出現什么現象呢?計算機會掛起嗎?你會得到"GeneralPRotection Exception”或內存信息轉儲這樣的消息嗎?請參見7.24中的討論。 例12.5a使用"string—n”函數的一個例子 # include <stdio. h> # include <string. h> /* Normally, a constant like MAXBUF would be very large, to help ensure that the buffer doesn't overflow. Here, it's very small, to show how the "string-n" functions prevent it from ever overflowing. */ # define MAXBUF 16 int main (int argc, char* * argv) { char buf[MAXBUF]; int i; buf[MAXBUF - 1] = '/0'; strncpy(buf, argv[0], MAXBUF-1); for (i = 1; i<argc; ++i) { strncat(buf, " " , MAXBUF -1 - strlen (buf) ) ; strncat(buf, argv[i], MAXBUF -1 - strlen (buf ) ) ; } puts (buf ); return 0; }
注重:許多字符串函數都至少有兩個參數,在描述它們時,與其稱之為“第一個參數”和“第二個參數”,還不如稱之為“左參數”和“右參數”。 函數strcpy()和strncpy()用來把字符串從一個數組拷貝到另一個數組,即把右參數的值拷貝到左參數中,這與賦值語句的順序是一樣的。 函數strcat()和strncat()用來把一個字符串連接到另一個字符串的末尾。例如,假如數組a1的內容為“dog”,數組a2的內容為“wood”,那么在調用strcat(al,a2)后,a1將變為“dogwood”。 函數strcmp()和strncmp()用來比較兩個字符串。當左參數小于、等于或大于右參數時,它們都分別返回一個小于、等于或大于零的值。常見的比較兩個字符串是否相等的寫法有以下兩種: if (strcmp(sl, s2)) { / * si !=s2 * / } 和 if (! strcmp(s1, s2)) { /* s1 ==s2 * / } 上述代碼可能并不易讀,但它們是完全有效并且相當常見的c代碼,你應該記住它們。假如在比較字符串時還需要考慮當前局部環境(locale,見12.8),則要使用strcoll()函數。 有一些函數用來在字符串中進行檢索(在任何情況下,都是在左參數或第一個參數中進行檢索)。函數strchr()和strrchr()分別用來查找某個字符在一個字符串中第一次和最后一次出現的位置(假如函數strchr()和strrchr()有帶“n”字母的版本,那么函數memchr()和memrchr()是最接近這種版本的函數)。函數strspn()、strcspn()(“c”表示"complement")和strpbrk()用來查找包含指定字符或被指定字符隔開的子字符串: n = strspn("Iowa" , "AEIOUaeiou"); / * n = 2( "Iowa" starts with 2 vowels * / n=strcspn("Hello world" ,"/t" ) ; / * n = 5; white space after 5 characters * / p = strbrk("Hellb world" ,"/t" ) ; / * p points to blank * /
函數strstr()用來在一個字符串中查找另一個字符串: p = strstr("Hello world", "or"); / * p points to the second "or" * /
函數strtok()按照第二個參數中指定的字符把一個字符串分解為若干部分。函數strtok()具有“破壞性”,它會在原字符串中插入NUL字符(假如原字符串還要做其它的改變,應該拷貝原字符串,并將這份拷貝傳遞給函數strtok())。函數strtok()是不能“重新進入”的,你不能在一個信號處理函數中調用strtok()函數,因為在下一次調用strtok()函數時它總是會“記住”上一次被調用時的某些參數。strtok()函數是一個古怪的函數,但它在分解以逗號或空白符分界的數據時是非常有用的。例12.5b給出了一個程序,該程序用strtok()函數把一個句子中的單詞分解出來: 例12.5b一個使用strtok()的例子 # include <stdio. h> # include <string. h> static char buf[] = "Now is the time for all good men . . . " ; int main() { char * p; p = strtok(buf, " ") ; while (p ) { printf("%s/n" ,p); p = strtok(NULL, " "); } return 0; }