字符串处理函数(strcpy 、strcat 、strcmp 、strlen)

头文件:#iclude<cstring>

字符串处理函数:strcpy(s1,s2)、strcmp(s1,s2)、strlen(s1)、strcat(s1,s2)

 1、strcpy(s1, s2)

说明:把字符串s2拷贝到s1,即s1的数据变成了s2的数据

注意:必须保证s1的内存空间大于或等于s2

#include<iostream>
#include<cstring>
using namespace std;
int main(){
	char str1[] = "123";
	char str2[] = "abc";

	cout<<strcpy(str1,str2);
}

//输出结果:abc

 2、strcmp(s1, s2)

说明:按照ASCII码顺序,s1和s2中的每个字符进行比较,

注意:当遇到某个字符不等时结束判断

返回值:比较结果。

  • 字符串1=字符串2,返回值=0;
  • 字符串1>字符串2,返回值>0,即 1;
  • 字符串1<字符串2,返回值<0,即 -1。
#include<iostream>
#include<cstring>
using namespace std;
int main(){
	char str1[] = "123456";
	char str2[] = "123456";
	char str3[] = "a23456";
	cout<<strcmp(str1,str2)<<"  "<<strcmp(str1,str3);
	
}

//输出结果为: 0   -1

3、strlen(s1)

作用:求字符数组或字符串的长度

#include<iostream>
#include<cstring>
using namespace std;
int main(){
	char str1[] = "123";
	char str2[] = "abcabc";
	
	cout<<strlen(str1)<<"  "<<strlen(str2);
}

//输出结果:3   6

 4、strcat(s1, s2)  

作用:把s2拼接到s1后面

#include<iostream>
#include<cstring>
using namespace std;
int main(){
	char s1[] = "123";
	char s2[] = "abc";

	cout<<strcat(s1,s2);
}

//输出结果:123abc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值