zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++ code:char pointers and char arrays(字符指针与字符数组)

C++字符code数组 and 指针 char Arrays
2023-09-14 09:01:23 时间

C-串的正确赋值、复制、修改、比较、连接等方式。

 1 #include<iostream>
 2 #pragma warning(disable: 4996)//这一句是为了解决“strrev”出现的警告
 3 using namespace std;
 4 int main()
 5 {
 6     char* s1 = "Hello ";
 7     char* s2 = "123";
 8     char a[20];
 9     strcpy(a,s1);
10     cout << (strcmp(a, s1) == 0 ? "" : " not") << "equal\n";
11     cout << strcat(a, s2) << endl;
12     cout << strrev(a) << endl;
13     cout << strset(a, 'c') << endl; 
14     cout << (strstr(s1, "ell") ? "" : "not ") << "found\n";
15     cout << (strchr(s1, 'c') ? "" : "not ") << "found\n";
16     cin.get();
17     return 0;
18 }

运行结果:

下面进入string:

string是一种自定义的类型,它可以方便地执行C-串不能直接执行的一切操作。它处理空间占用问题是自动的,需要多少,用多少,不像字符指针那样,提心吊胆于指针脱钩时的空间游离。

 1 #include<iostream>
 2 #include<string>
 3 #include<algorithm>
 4 using namespace std;
 5 int main()
 6 {
 7     string a,s1 = "Hello ";
 8     string s2 = "123";
 9     a=s1;//复制
10     cout << (a==s1 ? "" : " not") << "equal\n";//比较
11     cout << a + s2 << endl;//连接
12     reverse(a.begin(), a.end());//倒置串
13     cout << a << endl; 
14     cout << a.replace(0, 9, 9, 'c') << endl;//设置
15     cout << (s1.find("ell")!=-1 ? "" : "not ") << "found\n";//查找串
16     cout << (s1.find("c") != -1 ? "" : "not ") << "found\n";//查找字符
17     cin.get();
18     return 0;
19 }

运行结果: