本文最后更新于:5 个月前
- 想要在c语言中处理字符串,你需要引用<string.h>头文件
处理字符串的函数
strlen函数
函数声明
size_t strlen (const char *str);
作用:
返回字符串的长度(’\0’之前的长度,不包括’\0’)
注意:
参数指向的字符串必须要以‘\0’结束
示例
1 2 3 4 5 6 7 8 9
| #include <stdio.h> #include <string.h> int main(){ int n = 0; char str[6]="hello"; n = strlen(str); printf("%d",n); return 0; }
|
输出结果为5。
strcpy函数
函数声明
char * strcpy(char * destination,const * source);
作用:
把source字符串的内容复制到destination中
注意:
目标空间必须足够大能够存放源字符串
目标空间不可为”const”
示例
1 2 3 4 5 6 7 8 9 10 11
| #include <stdio.h> #include <string.h>
int main(){ char str1[6]="Hello"; char str2[6]="world"; printf("%s",str1); strcpy(str1,str2); printf("%s",str1); return 0; }
|
输出
strcat函数
函数声明
char * strcat(char * destination, const char * source)
;
作用:
将source的内容拼接到destination上
注意:
destination空间必须足够大
destination不能为”const”
不可以自己给自己拼接
示例
1 2 3 4 5 6 7 8 9 10 11
| #include <stdio.h> #include <string.h>
int main(){ char str1[20]="hello"; char str2[6]="world"; strcat(str1,str2); printf("%s",str1); return 0; }
|
输出
helloworld
strcmp函数
函数原型
int strcmp (const char * str1, const char * str2)
;
作用
比较两个字符串的大小
如果字符串1>字符串2,返回值>0
如果字符串1=字符串2,返回值=0
如果字符串1<字符串2,返回值>0
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <stdio.h> #include <string.h>
int main(){ char str1[10]="1234"; char str2[10]="1234567"; char str3[10]="123456789"; printf("%d\n",strcmp(str1,str3)); printf("%d\n",strcmp(str2,str2)); printf("%d\n",strcmp(str3,str1)); return 0; }
|
输出
strstr函数
函数声明
const char * strstr(const char * str1,const char * str2);
作用:
在str1中查找str2出现的位置
返回指向str1中第一次出现的str2的指针,如str2不是str1的一部分,则返回”NULL”
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <stdio.h> #include <string.h>
int main(){ char str1[10]="ABCDEFG"; char str2[10]="BCD"; char str3[10]="JOKER"; if(strstr(str1, str2) == NULL){ printf("NO\n"); } else{ printf("%s\n",strstr(str1,str2)); } if(strstr(str1, str3) == NULL){ printf("NO\n"); } else{ printf("%s\n",strstr(str1,str3)); } return 0; }
|
输出结果: