2023.10.24 C语言之字符串篇

本文详细介绍了C语言中的字符串处理函数,如gets与fgets的安全性、strcat拼接字符串、strcmp比较字符串、strlen获取长度、strlwr和strupr转换大小写,以及strstr查找子串。最后提到新的sprintf函数的应用。
摘要由CSDN通过智能技术生成

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函数已经不能使用了

image-20231024191352658

可用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博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值