【C语言】字符串操作


前言:字符串操作就是以串的整体作为操作对象,如:在串中查找某个子串、求取一个子串、在串的某个位置上插入一个子串以及删除一个子串等。
头文件为: #include <string.h>


一、字符串拷贝、拼接

字符串拷贝意义:把原本的字符串全部替换,变成另一个字符串
使用:strcpy(str1,str2)函数

	char str[20] = { '\0' };
	//字符串拷贝意义:把参数2赋值到参数1中,并且参数1原本的字符串被擦除
	//旧版:
	strcpy(str, "hello world");//"hello world"--->str
	printf("%s\n", str);
	//新版 区别:参数2为参数1的字节数,原因:防止越界
	strcpy_s(str, 20, "new strcpy_s");//参数2也可以:sizeof(str)
	printf("%s\n", str);

字符串拼接意义:两个字符串和在一起,原本的字符串不擦除
使用:strcat(str1,str2);

	 char str[40] = { '\0' };
	//字符串拷贝意义:两个字符串和在一起,原本的字符串不擦除
	//旧版:
	strcat(str, "hello world");//str中的字符串 + "hello world"
	printf("%s\n", str);
	//新版 区别:参数2为参数1的字节数,参数4为参数3的字节数
	strcat_s(str, 40, "new strcat_s",13);
	printf("%s\n", str);

将《一段》字符串插入到一个字符串的尾部
使用函数:strncat(str1,str2,int n);

	char str[40] = { '\0' };
	//旧版:
	strncat(str, "hello world",5);
	printf("%s\n", str);
	//新版 区别:参数4为要拷贝到str中的字节数
	strcat_s(str, 40, "new strcat_s",3);
	printf("%s\n", str);

二、字符串比较、长度

字符串比较意义:将字符串1和字符串2进行比较,比较的依据是谁的ascii在前,谁就大
使用函数:strcmp(str1,str2)
返回值:"0"一样大 "-1"后大 "1"前大

//从头开始比较
int a = strcmp("abc", "abc"); //一样大,返回 0   
int a = strcmp("abr", "abcde"); //前大,返回 1 
int a = strcmp("abcde", "ar"); //后大,返回-1

字符串比较前 n 个:从头依次比较,直到第一个不同的字符,此时谁大就谁大,否则相等
使用函数:strncmp(str1,str2,int n);
返回值和strcmp一样

int a = strncmp("ab", "abc", 1); //一样大,返回 0 
int a = strncmp("abr", "abcde", 2); //一样大,返回 0 
int a = strncmp("abcde", "ar", 2); //后大,返回-1

三、字符串长度

根据什么来判断是否结尾:'\0’字符 遇到\0直接返回 不计算\0字符
使用函数size_t t = strlen(str);
返回值为size_t 为字符串长度

size_t a = strlen("abcd"); //长度是 4 
size_t a = sizeof("abcd"); //5 个字节 
size_t a = strlen("abc\0def"); //长度是 3 
size_t a = sizeof("abc\0def"); //8 个字节
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人才程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值