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

版权声明:欢迎转载和交流。 https://blog.csdn.net/Hachi_Lin/article/details/79772451

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

猜你喜欢

转载自blog.csdn.net/Hachi_Lin/article/details/79772451
今日推荐