头文件:#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