C语言之字符串篇
字符串函数(#include<string.h>)
1,gets函数与puts函数
gets函数常用于读取一串数据直到读取到转行符为止,其常与puts函数连用
#include<stdio.h>
#include<string.h>
int main (void){
char s;
gets(s);
puts(s);
return 0;
}
但是gets函数也存在安全方面的缺点,详情请移步gets()的结构性缺陷和补救措施_gets有什么安全性缺陷_JokesForJoker的博客-CSDN博客
并且在c11之后,gets函数已经不能使用了
可用fgets函数代替gets函数使用fgets函数及其用法,C语言fgets函数详解-CSDN博客
2,strcat函数
作用是把两个字符数组中的字符串连接起来,把字符串2连接到字符串1的后面
#include<stdio.h>
#include<string.h>
int main (void){
//定义数组的两个注意点:
//①定义数组要有长度,即[]
//②初始化数组要用双引号""
char s1[10]="hello,";
char s2[10]="world!";
strcat(s1,s2);
printf("%s\n",s1);//输出结果为hello,world!
printf("%s",s2);//输出结果为world!
return 0;
}
//故strcat函数只是将s2添加到s1的末尾,s2本身并未发生改变。
3,strcmp函数
用于比较两个字符串是否相等
相等输出结果为0,前者大于后者输出结果为1,反之为-1
#include<stdio.h>
#include <string.h>
//初始化字符串数组要用双引号""
int main(void) {
char s0[10] = "hello";
char s1[10] = "hellooo";
char s2[10] = "he";
char s3[10] = "hello";
int x1 = strcmp(s0, s1); //x1=-1
int x2 = strcmp(s0, s2); //x2=1
int x3 = strcmp(s0, s3); //x3=0
return 0;
}
4,strlen函数
strlen函数常用于读取字符串的长度
#include<stdio.h>
#include<string.h>
int main (void){
char s[10086];
scanf("%s",s);
int x=strlen(s);
printf("%d",x);//x即为字符串s的长度
return 0;
}
7,strlwr函数(lower),strupr函数(upper)
使用格式为:
strlwr(s1);//直接将s1数组中的所有字母转化小写
8,strstr函数(从左到右),strrstr函数(从右到左)(废弃?)
利用strstr函数可以查找字符串中是否包含特定字符或字符集,有则输出该字符或字符集之后的所有字符,没有则返回null
#include<stdio.h>
#include<string.h>
int main (void){
//闭馆了...记得写完
//嗯嗯写完了已经
char s[100]="hello,world!";
char find1[100]="el";
char find2[100]=",";
char find3[100]="6";
printf("%s",strstr(s,find1));//输出结果为ello,world!
printf("%s",strstr(s,find2));//输出结果为,world!
printf("%s",strstr(s,find3));//输出结果为NULL
return 0;
}
9, strcpy函数(将一个数组复制到另一个数组中)
**2023.10.24 **
学到新的函数:sprintf()函数
详见:C语言的sprintf()函数详解。_sprintf头文件-CSDN博客
例题:P1957 口算练习题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
我看了gpt+看了答案调用sprintf函数才做出来…
该博客参考资料:
参考资料:字符串函数讲解(C语言笔记,建议收藏!!!)_字符串函数的笔记_我会一直在的的博客-CSDN博客