文章目錄
- 前言
- 1.字符分類函數
- 2.字符轉換函數
- 3.strlen的使用和模擬實現
- 4.strcpy的使用和模擬實現
- 5.strcat的使用和模擬實現
- 6.strncmp的使用和模擬實現
- 7.strncpy函數的使用
- 8.strncat函數的使用
- 9.strncmp函數的使用
- 10.strstr的使用和模擬實現
- 11.strtok函數的使用
- 12.strerror函數的使用
前言
在編程的過程中,我們經常要處理字符和字符串,為了方便操作字符和字符串,C語言標準庫中提供了?系列庫函數,接下來我們就學習一下這些函數。
1.字符分類函數
C語言中有一系列的函數時專門做字符分類的,也就是一個字符是屬于什么類型的字符的的。
這些函數的使用都需要包含一個頭文件ctype.h
函數 | 如果參數符合下列條件就返回真 |
---|---|
iscntrl | 任何控制字符 |
isspace | 空白字符:空格’ ‘,換頁’\f’,換行’\n’,回車’\r’,制表符’\t’或者垂直制表符’\v’ |
isdigit | 十進制數字 ’0‘ ~ ’9‘字符 |
isxdigit | 十六進制數字,包括所有十進制數字字符,小寫字母a-f,大寫字母A-F |
islower | 小寫字母a-z |
isupper | 大寫字母A-Z |
isalpha | 字母a-z 或者A-Z |
isalnum | 字母或者數字,a-z,A-Z,0-9 |
ispunct | 標點符號,任何不屬于數字或者字母的圖形字符 |
isgraph | 任何圖形字符 |
isprint | 任何可打印字符,包括圖形字符和空白字符 |
這些函數的使用方法非常類似,我們就用一個函數來舉個例子:
int islower(int c);
islower
函數能夠判斷參數部分的c
是否是小寫字母。
通過返回值來說明是否是小寫字母,如果是小寫字母就返回非0的整數,如果不是小寫字母,則返回0。
2.字符轉換函數
C語言中提供了2個字符轉換函數:
int tolower(int c);//將參數傳進去的大寫字母轉小寫
int toupper(int c);//將參數傳進去的小寫字母轉大寫
3.strlen的使用和模擬實現
size_t strlen(const char* str);
- 字符串以
\0
作為結束標志,strlen
函數返回的是在字符串中\0
前面出現的字符個數(不包含\0
)。 - 參數指向的字符串必須要以
\0
結束。 - 注意函數的返回值為
size_t
,是無符號的(易錯) strlen
的使用需要包含頭文件
示例代碼:
#include <stdio.h>
#include <string.h>
int main()
{const char* str1 = "abcdef";const char* str2 = "bbb";if (strlen(str2) - strlen(str1) > 0){printf("str2>str1\n");}else{printf("srt1>str2\n");}return 0;
}
strlen
的模擬實現:
方式1:
//計數器方式
int my_strlen(const char* str)
{int count = 0;assert(str);while (*str){count++;str++;}return count;
}
方式2:
//不能創建臨時變量計數器,使用遞歸的方式
int my_strlen(const char* str)
{assert(str);if (*str == '\0')return 0;elsereturn 1 + my_strlen(str + 1);
}
方式3:
//指針-指針的方式
int my_strlen(char* s)
{assert(s);char* p = s;while (*p != '\0')p++;return p - s;
}
4.strcpy的使用和模擬實現
char* strcpy(cahr* destination, const cahr* source);
- Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
- 來源字符串必須以
\0
結束。 - 會將來源字符串中的
\0
拷貝到目標空間。 - 目標空間必須足夠大,以確保能夠存放來源字符串。
- 目標空間必須可以修改。
strcpy
的模擬實現:
//1.參數順序
//2.函數的功能,停止條件
//3.assert
//4.const修飾指針
//5.函數返回值
//6.題目出自《高質量C/C++編程》書籍最后的試題部分
char* my_strcpy(char* dest, const char* src)
{char* ret = dest;assert(dest != NULL);assert(src != NULL);while ((*dest++ = *src++)){;}return ret;
}
5.strcat的使用和模擬實現
char * strcat ( char * destination, const char * source );
-
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
-
源字符串必須以
\0
結束。 -
目標字符串中也得有
\0
,否則沒辦法知道追加從哪里開始。 -
目標空間必須足夠的大,能夠容納源字符串的內容。
-
目標空間必須可修改。
-
字符串自己給自己追加,如何?
模擬實現strcat
函數:
char* my_strcat(char* dest, const char* src)
{char* ret = dest;assert(dest != NULL);assert(src != NULL);while (*dest){dest++;}while ((*dest++ = *src++)){;}return ret;
}
6.strncmp的使用和模擬實現
int strcmp ( const char * str1, const char * str2 );
-
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
-
標準規定:
- 第一個字符串大于第二個字符串,則返回大于0的數字
- 第一個字符串等于第二個字符串,則返回0
- 第一個字符串小于第二個字符串,則返回小于0的數字
- 那么如何判斷兩個字符串?答:比較兩個字符串中對應位置上的字符的ASCLL碼值的大小。
strcmp
函數的模擬實現:
int my_strcmp(const char* str1, const char* str2)
{int ret = 0;assert(str1 != NULL);assert(str2 != NULL);while (*str1 == *str2){if (*str1 == '\0')return 0;str1++;str2++;}return *str1 - *str2;
}
7.strncpy函數的使用
char * strncpy ( char * destination, const char * source, size_t num );
- Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before
num
characters have been copied, destination is padded with zeros until a total ofnum
characters have been written to it. - 拷貝
num
個字符從源字符串到目標空間。 - 如果源字符串的長度小于
num
,則拷貝完源字符串之后,在目標的后邊追加0,直到num
個。
8.strncat函數的使用
char * strncat ( char * destination, const char * source, size_t num );
- Appends the first
num
characters of source to destination, plus a terminating null-character.(將source指向字符串的前num
個字符追加到destination指向的字符串末尾,再追加?個\0
字符)。 - If the length of the C string in source is less than
num
, only the content up to the terminating null-character is copied.(如果source 指向的字符串的長度小于num
的時候,只會將字符串中到\0
的內容追加到destination指向的字符串末尾)。
示例代碼:
/* strncat example */
#include <stdio.h>
#include <string.h>
int main()
{char str1[20];char str2[20];strcpy(str1, "To be ");strcpy(str2, "or not to be");strncat(str1, str2, 6);printf("%s\n", str1);return 0;
}
9.strncmp函數的使用
int strncmp ( const char * str1, const char * str2, size_t num );
比較str1
和str2
的前num
個字符,如果相等就繼續往后比較,最多比較num
個字母,如果提前發現不一樣,就提前結束,大的字符所在的字符串大于另外一個。如果num
個字符都相等,就是相等返回0。
10.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
作為結束標志)。
示例代碼:
#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
的模擬實現:
const char* my_strstr(const char* str1, const char* str2)
{assert(str1 && str2);const char* s1 = NULL;const char* s2 = NULL;const char* cur = str1;//特殊情況 - str2指向的是空字符串,直接返回str1if (*str2 == '\0')return str1;while (*cur){s1 = cur;s2 = str2;while (*s1 && *s2 && *s1 == *s2){s1++;s2++;}if (*s2 == '\0')return cur;cur++;}return NULL;
}
11.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);}//這里巧妙的使用了for循環,使得初始化部分strtok只執行一次,然后都是調整部分strtok的執行。return 0;
}
12.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+VS2019環境下輸出的結果如下:
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