c++字符数组函数总结字符串函数连接
1.strcat()
格式:
  strcat(字符数组1,字符数组2)
作⽤:
  字符串连接函数,其功能是将字符数组2中的字符串连接到字符数组1中字符串的后⾯,并删去字符串1后的串结束标志”\0”。需要注意的是字符数组的长度要⾜够⼤,否则不能装下连接后的字符串。
例⼦:
1 #include <bits/stdc++.h>
2using namespace std;
3int main() {
4char str1[30], str2[20];
5    cout << "please input string1:" << endl;
6    cin >> str1;
7    cout << "please input string2:" << endl;
8    cin >> str2;
9    strcat(str1, str2);
10    cout << "Now the string is:" << endl;
11    cout << str1 << endl;
12return0;
13 }
运⾏结果:
2.strcpy()
格式:
strcpy(字符数组1,字符数组2)
说明:
  字符串复制函数,其功能是把数组2中的字符串复制到字符数组1中。字符串结束标志”\0”也⼀同复制。要求字符数组1应有⾜够的长度,否则不能全部装⼊所复制的字符串。另外,字符数组1必须写成数组名形式,⽽字符数组2可以是字符数组名,也可以是⼀个字符串常量。
例⼦:
1 #include <bits/stdc++.h>
2using namespace std;
3int main() {
4char str1[30], str2[20];
5    cin >> str1; //给str1赋值
6    cout << "str1为:" << str1 << endl;
7    strcpy(str2, "456789"); //给str2赋值
8    cout << "str2为:" << str2 << endl;
9    strcpy(str1, str2);
10    cout << "str1为:" << str1 << endl;
11return0;
12 }
运⾏结果:
3.strcmp()
格式:
strcmp(字符数组1,字符数组2)
说明:
  字符串⽐较函数,其功能是按照ASCII码顺序⽐较两个数组中的字符串,并有函数返回⽐较结果。如果字符串1=字符串2,返回0;如果字符串1>字符串2,返回正数;如果字符串1<;字符串2,返回值负数。
例⼦:
1 #include <bits/stdc++.h>
2using namespace std;
3int main() {
4char str1[30], str2[30];
5    cin >> str1;
6    cout << "str1为:" << str1 << endl;
7    cin >> str2;
8    cout << "str2为:" << str2 << endl;
9    cout << strcmp(str1, str2) << endl;
10return0;
11 }
运⾏结果:
4.strncmp()
格式:
strncmp(字符数组1,字符数组2,长度n)
说明:
  同strcmp()函数,加⼊了要⽐较的最⼤字符数n。例⼦:
1 #include <bits/stdc++.h>
2using namespace std;
3int main() {
4char str1[30], str2[30];
5    cin >> str1;
6    cout << "str1为:" << str1 << endl;
7    cin >> str2;
8    cout << "str2为:" << str2 << endl;
9int n;
10    cin >> n;
11    cout << "n为:" << n << endl;
12    cout << strncmp(str1, str2, n) << endl;
13return0;
14 }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。