Linux下C语言字符串操作之连接和查找

6100阅读 0评论2013-03-24 zhengb302
分类:C/C++

1,字符串连接
char *strcat(char *dest, const char *src);
char *strncat(char *dest, const char *src, size_t n);
英文manual并不难,直接上英文:
The  strcat()  function appends the src string to the dest string, over‐writing the terminating null byte ('\0') at the end of  dest,  and  then adds a terminating null byte.The strings may not overlap, and the dest string must have enough space for the result.The strncat() function is similar, except that
       *  it will use at most n characters from src; and
       *  src does not need to be null-terminated if  it  contains  n  or  more characters.
As  with  strcat(),  the  resulting string in dest is always null-terminated. If src contains n or more characters, strncat() writes n+1 characters to dest  (n  from src plus the terminating null byte).  Therefore, the size of dest must be at least strlen(dest)+n+1.
返回值:The strcat() and strncat() functions return a pointer to  the  resulting string dest.
示例代码:
  1. #include <stdio.h>
  2. #include <string.h>

  3. int main(){
  4.     char *src="world";
  5.     char dest[100]="hello ";
  6.     strcat(dest,src);
  7.     printf("strcat result: %s, strlen: %d\n",dest,(int)strlen(dest));
  8.     return 0;
  9. }
输出:
strcat result: hello world, strlen: 11

2,字符串查找
char *strstr(const char *haystack, const char *needle);
char *strcasestr(const char *haystack, const char *needle);
说明:The strstr() function finds the first occurrence of the substring needle in the string haystack.  The terminating null bytes ('\0') are not  compared. The strcasestr() function is like strstr(), but ignores the case of both arguments.
返回值:These functions return a pointer to the beginning of the  substring,  or NULL if the substring is not found.
示例代码:
  1. #include <stdio.h>
  2. #include <string.h>

  3. int main(){
  4.     char *src="hello world,I am a strstr example";
  5.     char *psubstr=strstr(src,"am");
  6.     printf("strstr result: %s\n",psubstr);
  7.     return 0;
  8. }
输出:
strstr result: am a strstr example


上一篇:Linux下C语言字符串操作之分割字符串
下一篇:Linux下C语言字符串操作之字符串转数值型