c++关于字符数组的处理函数

本文详细介绍了C++中处理字符数组的四个关键函数:strcat用于字符串连接,strcpy实现字符串复制,strcmp用于字符串比较,strlen则用于计算字符串长度。每个函数的使用方法、注意事项及示例代码都进行了清晰的说明。

1.strcat函数

具体格式:

strcat(字符数组1,字符数组2)

说明:
字符串连接函数,其功能是将字符数组2中的字符串连接到字符数组1中字符串的后面,并删去字符串1后的串结束标志”\0”。需要注意的是字符数组的长度要足够大,否则不能装下连接后的字符串。

例子:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main(){
   char str1[30],str2[20];
   cout<<"please input string1:"<<endl;
   gets(str1);
   cout<<"please input string2:"<<endl;
   gets(str2);
   strcat(str1,str2);
   cout<<"Now the string is:"<<endl;
   puts(str1);
   return 0;
}

运行结果:

please input string1:
123
please input string2:
456
Now the string is:
123456

2.strcpy函数

格式:

strcpy(字符数组1,字符数组2)

说明:
字符串复制函数,其功能是把数组2中的字符串复制到字符数组1中。字符串结束标志”\0”也一同复制。要求字符数组1应有足够的长度,否则不能全部装入所复制的字符串。另外,字符数组1必须写成数组名形式,而字符数组2可以是字符数组名,也可以是一个字符串常量,这时相当于把一个字符串赋予一个字符数组。

例子:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main(){
   char str1[30],str2[20];
   cout<<"please input string1:"<<endl;
   gets(str1);
   cout<<"please input string2:"<<endl;
   gets(str2);
   strcpy(str1,str2);
   cout<<"Now the string is:"<<endl;
   puts(str1);
   return 0;
}

运行结果:

please input string1:
123
please input string2:
456789
Now the string is:
456789

3.strcmp函数

格式:

strcmp(字符数组1。字符数组2)

说明:
字符串比较函数,其功能是按照ASCII码顺序比较两个数组中的字符串,并有函数返回比较结果。如果字符串1=字符串2,返回0;如果字符串1>字符串2,返回为1正数;如果字符串1<字符串2,返回值为一负数。需要注意的是进行比较时若出现不同的字符,则以第一个不同的字符的比较结果作为整个比较的结果。

例子:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main(){
   char str1[30],str2[20];
   cout<<"please input string1:"<<endl;
   gets(str1);
   cout<<"please input string2:"<<endl;
   gets(str2);
   cout<<strcmp(str1,str2);
   return 0;
}

运行结果:

例一:
please input string1:
abc
please input string2:
abcd
-1
例二:
please input string1:
abda
please input string2:
abcf
1

4.strlen

格式:

strlen(字符数组名)

说明:
其功能是测字符数串的实际长度(不含字符串的结束标志”\0”),函数返回值为字符串的实际长度。

例子:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main(){
   char str1[30],str2[20];
   cout<<"please input string1:"<<endl;
   gets(str1);
   cout<<"please input string2:"<<endl;
   gets(str2);
   int len1 = strlen(str1);
   int len2 = strlen(str2);
   cout<<"the length of string1 is ":<<len1<<endl;
   cout<<"the length of string2 is ":<<len2<<endl;
   return 0;
}

运行结果:

please input string1:
abc
please input string2:
abcde
the length of string1 is :3
the length of string2 is :5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值