C 常见字符串操作函数
头文件 <string.h>
1. char *strstr(const char *str1, const char *str2); 判断str2是否为str1的子串
//str1中包含str2子串情况
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char *str1 = "hello world!";
char *str2 = "world";
char *p = strstr(str1,str2);
printf("str1 = %p :%s\n",str1,str1);
printf("str2 = %p :%s\n",str2,str2);
printf("p = %p :%s\n",p,p);
return 0;
}
输出结果
//str1中不包含str2子串情况
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char *str1 = "hello world!";
char *str2 = "world";
char *p = strstr(str2,str1);
printf("str1 = %p :%s\n",str1,str1);
printf("str2 = %p :%s\n",str2,str2);
printf("p = %p :%s\n",p,p);
return 0;
}
输出结果:
2. char *strcat(char *dest, const char *src);
将字符串src头拼接在dest的'\0'位置,在重新拼接的字符串后重新添加 '\0' ;注意事项dest空间足够大
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char dest[20] = "hello";
char *src = "world";
char *p = strcat(dest,src);
printf("dest = %p :%s\n",dest,dest);
printf("src = %p :%s\n",src,src);
printf("p = %p :%s\n",p,p);
return 0;
}
运行结果:dest 要足够大不然包段错误
3. char *strncat(char *dest, const char *src, size_t n);
把src所指字符串的前n个字符添加到dest所指字符串的结尾处,并覆盖dest所指字符串结尾的'\0',从而实现字符串的连接
#include <stdio.h> #include <string.h> int main(int argc, const char *argv[]) { char dest[10] = "hello "; char *src = "world"; char *p = strncat(dest,src,3); printf("dest = %s\n",dest); printf("src = %s\n",src); printf("p = %s\n",p); return 0; }
输出结果:
4. char *strcpy(char *dest, const char *src);
把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间
#include <stdio.h> #include <string.h> int main(int argc, const char *argv[]) { char dest[20] = "hello world!"; char *src = "world"; char *p = strcpy(dest,src); printf("dest = %p :%s\n",dest,dest); printf("src = %p :%s\n",src,src); printf("p = %p :%s\n",p,p); int len = sizeof(dest); int i=0; printf("dest[] = "); for(i=0;i<len;i++) { printf("%c",dest[i]); } putchar(10); printf("十进制打印\n"); for(i=0;i<len;i++) { printf("%d\n",dest[i]); } putchar(10); return 0; }
输出结果:
5. char *strncpy(char *dest, const char *src, size_t n);
把src所指向的字符串中以src地址开始的前n个字节复制到dest所指的数组中,并返回被复制后的dest。
#include <stdio.h> #include <string.h> int main(int argc, const char *argv[]) { char dest[20] = "hello"; char *src = "world"; char *p = strncpy(dest,src,1); printf("dest = %p :%s\n",dest,dest); printf("src = %p :%s\n",src,src); printf("p = %p :%s\n",p,p); return 0; }
输出结果:
6. int strcmp(const char *str1, const char *str2);
7. int strncmp(const char *str1, const char *str2, size_t n);
str1, str2 为需要比较的两个字符串,n为要比较的字符的数目。
#include <stdio.h> #include <string.h> int main(int argc, const char *argv[]) { char dest[20] = "hello world!"; char *src = "hellod"; int num = strncmp(src,dest,4); printf("num = %d\n",num); return 0; }
8. 字符串分割函数
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);