c++字符数组函数总结

参考于https://blog.csdn.net/Hachi_Lin/article/details/79772451

1.strcat()
格式:

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

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4    char 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;
12    return 0;
13 }

运行结果:

c++字符数组函数总结

2.strcpy()
格式:
    strcpy(字符数组1,字符数组2)
说明:
  字符串复制函数,其功能是把数组2中的字符串复制到字符数组1中。字符串结束标志””也一同复制。要求字符数组1应有足够的长度,否则不能全部装入所复制的字符串。另外,字符数组1必须写成数组名形式,而字符数组2可以是字符数组名,也可以是一个字符串常量。
例子:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4    char 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;
11    return 0;
12 }

运行结果:

c++字符数组函数总结

 3.strcmp()
格式:
    strcmp(字符数组1,字符数组2)
说明:
  字符串比较函数,其功能是按照ASCII码顺序比较两个数组中的字符串,并有函数返回比较结果。如果字符串1=字符串2,返回0;如果字符串1>字符串2,返回正数;如果字符串1<字符串2,返回值负数。
例子:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4    char 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;
10    return 0;
11 }

运行结果:

c++字符数组函数总结

c++字符数组函数总结

 c++字符数组函数总结

c++字符数组函数总结

4.strncmp()

格式:
    strncmp(字符数组1,字符数组2,长度n)
说明:
  同strcmp()函数,加入了要比较的最大字符数n。
例子:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4    char str1[30], str2[30];
 5    cin >> str1; 
 6    cout << "str1为:" << str1 << endl; 
 7    cin >> str2; 
 8    cout << "str2为:" << str2 << endl; 
 9    int n;
10    cin >> n;
11    cout << "n为:" << n << endl; 
12    cout << strncmp(str1, str2, n) << endl;
13    return 0;
14 }

c++字符数组函数总结

c++字符数组函数总结

 

原文链接: https://www.cnblogs.com/fx1998/p/12611710.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++字符数组函数总结

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/339093

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:56
下一篇 2023年3月1日 下午11:56

相关推荐