1. strstr的使用和模擬實現
char * strstr ( const char * str1, const char * str2);
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1. (函數返回字符串str2在字符串str1中第?次出現的位置)。
The matching process does not include the terminating null-characters, but it stops there.(字符 串的比較匹配不包含 \0 字符,以 \0 作為結束標志)。
/* strstr example */
#include <stdio.h>
#include <string.h>
int main ()
{char str[] ="This is a simple string";char * pch;pch = strstr (str,"simple");strncpy (pch,"sample",6);printf("%s\n", str);return 0;
}
strstr的模擬實現:
char * strstr (const char * str1, const char * str2)
{char *cp = (char *) str1;char *s1, *s2;if ( !*str2 )return((char *)str1);while (*cp){s1 = cp;s2 = (char *) str2;while ( *s1 && *s2 && !(*s1-*s2) )s1++, s2++;if (!*s2)return(cp);cp++;}return(NULL);
}
2. strtok函數的使用
char * strtok ( char * str, const char * sep);
? sep參數指向?個字符串,定義了?作分隔符的字符集合
? 第?個參數指定?個字符串,它包含了0個或者多個由sep字符串中?個或者多個分隔符分割的標 記。
? strtok函數找到str中的下?個標記,并將其? \0 結尾,返回?個指向這個標記的指針。(注:
strtok函數會改變被操作的字符串,所以在使?strtok函數切分的字符串?般都是臨時拷?的內容 并且可修改。)
? strtok函數的第?個參數不為 NULL ,函數將找到str中第?個標記,strtok函數將保存它在字符串 中的位置。
? strtok函數的第?個參數為 NULL ,函數將在同?個字符串中被保存的位置開始,查找下?個標 記。
? 如果字符串中不存在更多的標記,則返回 NULL 指針。
#include <stdio.h>
#include <string.h>
int main()
{char arr[] = "192.168.6.111";char* sep = ".";char* str = NULL;for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep)){printf("%s\n", str);}return 0;
}
3. strerror函數的使用
char * strerror ( int errnum );
strerror函數可以把參數部分錯誤碼對應的錯誤信息的字符串地址返回來。
在不同的系統和C語?標準庫的實現中都規定了?些錯誤碼,?般是放在 errno.h 這個頭?件中說明的,C語?程序啟動的時候就會使用一個全面的變量errno來記錄程序的當前錯誤碼,只不過程序啟動的時候errno是0,表?沒有錯誤,當我們在使用標準庫中的函數的時候發?了某種錯誤,就會講對應的錯誤碼,存放在errno中,而?個錯誤碼的數字是整數很難理解是什么意思,所以每?個錯誤碼都是有對應的錯誤信息的。strerror函數就可以將錯誤對應的錯誤信息字符串的地址返回。
#include <errno.h>
#include <string.h>
#include <stdio.h>
//我們打印?下0~10這些錯誤碼對應的信息
int main()
{int i = 0;for (i = 0; i <= 10; i++) {printf("%s\n", strerror(i));}return 0;
}
在Windows11+VS2022環境下輸出的結果如下:
No error
Operation not permitted
No such file or directory
No such process
Interrupted function call
Input/output error
No such device or address
Arg list too long
Exec format error
Bad file descriptor
No child processes
舉例:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main ()
{FILE * pFile;pFile = fopen ("unexist.ent","r");if (pFile == NULL)printf ("Error opening file unexist.ent: %s\n", strerror(errno));return 0;
}
輸出:
Error opening file unexist.ent: No such file or directory
也可以了解?下perror函數,perror 函數相當于一次將上述代碼中的第9行完成了,直接將錯誤信息打印出來。perror函數打印完參數部分的字符串后,再打印一個冒號和一個空格,再打印錯誤信息。
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main ()
{FILE * pFile;pFile = fopen ("unexist.ent","r");if (pFile == NULL)perror("Error opening file unexist.ent");return 0;
}
輸出:
Error opening file unexist.ent: No such file or directory