C語言處理字符串極為不便,幸好庫函數提供了還算豐富的處理字符串的函數。有一些函數我們平時不大用的到,不過了解一下總是好的,知道有這麼個東西,下次要用的時候再去查一下手冊就好了。
這裡介紹的函數主要有:strcat, strcmp, strcasecmp, strcpy, strdup, strlen, strchr, strrchr, strstr, strpbrk, strspn, strcspn, strtok. 在本章的最後還會給出這些庫函數的具體實現,以應付一些企業的面試。
文章共分四個部分,第一部分直接列出了常用的字符串處理函數,由於這些都是大家平時接觸的比較多的,在此不再多說;第二部分介紹了不太常用的字符串處理函數,並給出了具體示例,很多函數看名字很難猜到它的具體作用,但是一個小小的例子就能解釋得很清楚;第三部分給出了這些函數的具體實現,大部分參考網上個人認為已經不錯的實現,部分是查看glibc源代碼後,簡化得來的程序;第四部分作者非常道德的給出了參考資料。
常用的字符串處理函數:
char *strcat(char *s1, const char *s2);
char *strncat(char *s1, const char *s2);
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t length);
int strcasecmp(const char *s1, const char *s2);
int strncasecmp(const char *s1, const char *s2, size_t length);
char *strcpy(char *s1, const char *s2);
char *strncpy(char *s1, const char *s2, size_t length);
size_t strlen(const char *s1);
不太常用的字符串處理函數:
//the strdup() function allocates memory and copies into it the string addressed s1. including the terminating null character.
//It is the use's responsibility to free the allocated storage by calling free()
char *strdup(const char *s1);
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- int main(int argc, char* argv[])
- {
- char str[] = "this is a example";
- char *p = NULL;
- if ((p = strdup(str)) != NULL)
- {
- printf("strlen(p) = %d \t sizeof(p) = %d\n", strlen(p), sizeof(p));
- printf("strlen(str) = %d\t sizeof(str) = %d\n", strlen(str), sizeof(str));
- if ( p == str )
- {
- puts("p == str");
- }
- else
- {
- puts("p != str");
- }
- }
- free(p);
- p = NULL;
- return 0;
- }
output:
www.linuxidc.com@Ubuntu:~/temp$ ./a.out
strlen(p) = 17 sizeof(p) = 4
strlen(str) = 17 sizeof(str) = 18
p != str
//locate first occurrence of character in string
char *strchr(const char *s1, int c);
- #include <stdio.h>
- #include <string.h>
-
- int main(int argc, char* argv[])
- {
- char str[] = "This is a sample string";
- char *pch;
- pch = strchr(str, 's');
- while (pch != NULL)
- {
- printf("found at %d\n", pch - str + 1);
- pch = strchr(pch + 1, 's');
- }
- return 0;
- }
output:www.linuxidc.com@ubuntu:~/temp$ ./a.out
found at 4
found at 7
found at 11
found at 18
// locate last occurrence of character in string
char *strrchr(const char *s1, int c);
- #include <stdio.h>
- #include <string.h>
-
- int main(int argc, char* argv[])
- {
- char str[] = "This is a sample string";
- char *pch;
- pch = strrchr(str, 's');
- printf("found at %d\n", pch - str + 1);
- return 0;
- }