【C】常用的字符串函数

1. strcpy

  函数名:strcpy

  用法:char *strcpy(char *destin, char *cource)

  功能:将一个字符串从一个拷贝到另外一个

  程序示例:

  

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(){
 5   char str1[] = "source";
 6   char str2[] = "des";
 7 
 8   strcpy(str1,str2);
 9   printf("str1 : %s\n",str1);
10   return 0;
11 }

  程序输出:

  

2. strnpy

  函数名:strnpy

  用法:char * strncpy(char *dest, char *src,size_t n);

  功能:将字符串src中的前n个字符复制到字符串数组dest中,注意(不会清除dest数组中原来的数据,只是将新的数据覆盖)

  程序示例:

  

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(){
 5   char str1[] = "source";
 6   char str2[] = "dest";
 7 
 8   strncpy(str1,str2,4);
 9   printf("str1 : %s\n",str1);
10   return 0;
11 }

  程序结果:(注意,函数没有清理原数组)

  

 

3.strcat

  函数名:strcat

  用法: char *strcat(char *destin, char *source)

  功能:将source 拼接到 destin 字符串后

  程序示例

  

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(){
 5   char str1[] = "source";
 6   char str2[] = "dest";
 7 
 8   // strcpy(str1,str2);
 9   strcat(str1,str2);
10   printf("str1 : %s\n",str1);
11   return 0;
12 }

  程序输出

  

4. strchr

  函数名:strchr

  用法:char *strchr(char *str, char *c);

  功能:在str 字符串中查找字符(串)c 得匹配之处,返回该指针,如果没有返回NULL

  程序实例:

  

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(){
 5   char str1[] = "source";
 6   char str2 = 'c';
 7 
 8   // strcpy(str1,str2);
 9   char *strFind = strchr(str1,str2);
10   printf("strFind : %c\n",*strFind);
11   return 0;
12 }

 

  程序结果:

  

 

  

 

posted @ 2017-07-21 19:11  三生石1314  阅读(449)  评论(0编辑  收藏  举报