前言
字符串处理函数有很多,我们不必全部记住,等到要用的时候,我们可以再上网搜索学习,所以今天我为大家带来了几个我认为比较常用的字符串函数。
一、常用函数
- strcpy:字符串拷贝函数
- strlen:求字符串长度函数
- strcat:字符串拼接函数
- strcmp:字符串比较函数
- strtok:字符串截取函数
二、函数详解
直接用代码交流吧!
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char s1[32] = "www.hqyjfarsight.com";
char s2[12] = "hello world";
printf("s1 = %s\n",s1);
printf("s2 = %s\n",s2);
printf("------------------------\n");
#if 0
/*************************************
*1.strcpy
*功能:
* 将一个字符串的内容复制到另一个字符串,包括\0
*头文件:
* #include<string.h>
*函数原型:
* char *strcpy(char *dest,const char *src);
*参数:
* dest:目的字符串
* src:源字符串
*返回值:
* 返回目的字符串,等同于dest
*注意:
* 一定要保证dest足够大
************************************/
strcpy(s1,s2);
printf("s1 = %s\n",s1);
printf("s2 = %s\n",s2);
//复制后,s1后面的字符串还在,只不过被\0隔开了
//用%s将不能打印出来,可以用%c打印
printf("%c\n",s1[12]);
#endif
#if 0
/**************************************
*2.strlen
*功能:
* 计算一个字符串的长度,不包括'\0'
*头文件:
* #include <string.h>
*函数原型:
* zize_t strlen(const char *s);
*参数:
* s:需要计算长度的字符串
*返回值:
* 计算后的字符串长度
**************************************/
size_t ret = strlen(s2);
printf("strlen(s2) = %ld\n",ret);
//strlen不能求字符数组的长度
//因为他求的结果不包括\0,而且计算字符数量时,只有检测到\0时,才会停止计数
//但是计算过程是以\0为准的
//这样会出现返回的长度与数组真实长度不一致的情况
//如,不能求这种类型的字符数组长度
char s[5] = {'a','b','c','d','e'};
//这样也不行,这样求出来的长度会比真实长度小1
char s9[5] = {'a','b','c','d','\0'};
printf("strlen(s) = %ld\n",strlen(s));
#endif
#if 0
/**************************************
*3.strcat
*功能:
* 将一个字符串拼接到另外一个字符串后面,会覆盖目的字符串的'\0'
*头文件:
* #include <string.h>
*函数原型:
* char *strcat(char *dest,const char *src);
*参数:
* dest:目的字符串
* src:源字符串
*返回值:
* 返回目的字符串,等同于dest
**************************************/
strcat(s1,s2);
printf("s1 = %s\n",s1);
printf("s2 = %s\n",s2);
#endif
#if 1
/**************************************
*4.strcmp
*功能:
* 比较两个字符串的大小,比较规则:
* 字符串大小比较比较的是两个字符串ASCII的值的大小
* strcmp()首先将两个字符串的第一个字符的ASCII的值
* 若差值为0,则比较下一个,否则立即返回。
*头文件:
* #include <string.h>
*函数原型:
* int *strcmp(const char *s1,const char *s2);
*参数:
* s1:参与比较的字符串
* s2:参与比较的字符串
*返回值:
* 返回两个字符串的差值,这个值有以下情况
* >0:s1>s2
* =0:s1=s2
* <0:s1<s2
**************************************/
int ret = strcmp(s1,s2);
if(ret > 0){
printf("s1 > s2\n");
}else if(ret < 0){
printf("s1 < s2\n");
}else{
printf("s1 = s2\n");
}
printf("'w' - 'h' = %d\n",'w' - 'h');
printf("strcpm(s1,s2) = %d\n",ret);
#endif
return 0;
}
三、其它字符串函数
- strncpy(char *dest, const char *src, size_t n):复制指定长度字符串
- strncat(char *dest, const char *src, size_t n):附加指定长度字符串
- strcasecmp(const char *s1, const char *s2):忽略大小写比较字符串
- strncmp(const char * str1, const char * str2, size_t n):比较指定字符串长度
- strchr(const char* str, int c):在字符串中查找指定字符
- strstr(char *str, char * substr):查找字符串
总结
使用字符串的时候要注意,只有含有'\0'的时候的一串字符才能被称为是一个字符串,而字符串一定会含有一个'\0'。