歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C/C++字符串處理函數

C/C++字符串處理函數

日期:2017/3/1 10:21:16   编辑:Linux編程
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);
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int main(int argc, char* argv[])
  5. {
  6. char str[] = "this is a example";
  7. char *p = NULL;
  8. if ((p = strdup(str)) != NULL)
  9. {
  10. printf("strlen(p) = %d \t sizeof(p) = %d\n", strlen(p), sizeof(p));
  11. printf("strlen(str) = %d\t sizeof(str) = %d\n", strlen(str), sizeof(str));
  12. if ( p == str )
  13. {
  14. puts("p == str");
  15. }
  16. else
  17. {
  18. puts("p != str");
  19. }
  20. }
  21. free(p);
  22. p = NULL;
  23. return 0;
  24. }
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);

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main(int argc, char* argv[])
  4. {
  5. char str[] = "This is a sample string";
  6. char *pch;
  7. pch = strchr(str, 's');
  8. while (pch != NULL)
  9. {
  10. printf("found at %d\n", pch - str + 1);
  11. pch = strchr(pch + 1, 's');
  12. }
  13. return 0;
  14. }
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);

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main(int argc, char* argv[])
  4. {
  5. char str[] = "This is a sample string";
  6. char *pch;
  7. pch = strrchr(str, 's');
  8. printf("found at %d\n", pch - str + 1);
  9. return 0;
  10. }
Copyright © Linux教程網 All Rights Reserved