字符串处理函数
字符串操作函数,必须包括的头文件,
#include<string.h>
gets()
#include <stdio.h>
int main(int argc,char *argv[]){
char s[100]={
0};
gets(s);
//gets认为回车是结束标识,空格不是输入结束标识,所以用gets这个函数就可以实现输入带空格的字符串
//gets同样和scanf一样存在缓冲区溢出的问题
for(int i=0;i<10;i++){
printf("%d\n",s[i]);
}
printf("--------------\n");
printf("%s\n",s);
return 0;
}
/Users/Xx/CLionProjects/Struct1/cmake-build-debug/Struct1
warning: this program uses gets(), which is unsafe.
hello word
104
101
108
108
111
32
119
111
114
100
--------------
hello word
Process finished with exit code 0
gets函数不能类似"%s"或者"%d"之类的字符转义,只能接收字符串的输入,get(s)这里只能接受字符串s。引入下文的atoi(),字符串的不同类型之间的转换。
fgets()
#include <stdio.h>
int main(int argc,char *argv[]){
char s[10]={
0};
fgets(s,10//sizeof(s)-1,stdin);
//s参数是char的数组,100是数组的大小(单位:字节),stdin是标准输入的意思
printf("%s\n",s);
return 0;
}
/Users/Xx/CLionProjects/Struct1/cmake-build-debug/Struct1
0123456789abc
012345678
Process finished with exit code 0
这里输出的是9位,有一位字符串结束标识符"\0"。
fgets()是安全的,不会出现缓冲区溢出的问题,调用fgets()的时候,只要保证第二个参数小于数组的实际大小,那么久不会出现缓冲区溢出的问题。
puts()打印输出字符串
#include <stdio.h>
int main(int argc,char *argv[]){
char s[10]={
0};
fgets(s, sizeof(s)-1,stdin);
puts(s);
return 0;
}
/Users/Xx/CLionProjects/Struct1/cmake-build-debug/Struct1
hello word
hello wo
Process finished with exit code 0
puts()函数自动会在输出完成之后打印一个"\n"出来。
fputs()函数
同上
strlen() 得到字符串长度
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[]){
char s[100]="hello world";
int len = strlen(s);
//得到字符串的长度,返回一个字符串中有效字符的数量(不包含字符串中结尾的'\0')
printf("%d",len);
return 0;
}
/Users/Xx/CLionProjects/Struct1/cmake-build-debug/Struct1