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 sizeof(p) = %d
", strlen(p), sizeof(p));
- printf("strlen(str) = %d sizeof(str) = %d
", 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
", 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
", pch - str + 1);
- return 0;
- }