C语言-06字符串处理函数

本文介绍了C语言中常用的字符串处理函数,包括gets(), fgets(), puts(), fputs(), strlen(), strcat(), strncat(), strcmp(), strncmp(), strcpy(), strncpy(), sprintf(), sscanf(), strchr(), strstr()和strtok()等。讨论了它们的功能、使用方法以及安全注意事项,例如防止缓冲区溢出。还提到了字符串转换函数如atoi(), atof()和atol()。" 108173946,7513809,Flink Table API与SQL实战,"['Flink', '大数据处理', 'SQL', '流处理', '批处理']
摘要由CSDN通过智能技术生成

字符串处理函数
字符串操作函数,必须包括的头文件,
#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值