C++中字符串的两种表示方法:
1。C 风格的字符串
2。标准 C++引入的string 类类型
C风格的例子:(计算字符串的长度)
1 #include<iostream>
2 #include<string>
3 #include<cstring>
4 using namespace std;
5 int main()
6 {
7 const char *str = "The expense of spirit!";
8 int len = 0;
9 const char *p = str;
10 while(*p++){
11 ++len;
12 }
13 cout << len << ": " << str << endl;
14
15 return 0;
16 }
编译:$ g++ string.c
运行:$ ./a.out
结果:22: The expense of spirit!
C++字符串类型的例子:
1 #include<string>
2 #include<iostream>
3 using namespace std;
4 int main()
5 {
6 string str("The expense of spirit!");//第一种构造函数的形式
7 string str2;//第二种构造函数的形式
8 if(!str2.size())
9 cout << "str2 is null/n";
10 if(str.empty())
11 cout << "str is null/n";
12 else
13 cout << "The size of /""
14 << str
15 << "/" is " << str.size()
16 << endl;
17
18 //将str初始化给str3
19 string str3( str );
20 cout << "str3 :" << str3 << endl;
21 cout << "========================/n";
22 string s1("Hello, ");
23 string s2("World!/n");
24 string s3 = s1 + s2;
25 cout << "s3: " << s3;
26 return 0;
27 }
编译:$g++ string_C++.c
运行:$./a.out
结果:
str2 is null
The size of "The expense of spirit!" is 22
str3 :The expense of spirit!
========================
s3: Hello, World!
下面是C风格和C++风格混用的例子:
1 #include<iostream>
2 #include<string>
3 #include<cstring>
4 using namespace std;
5 int main()
6 {
7 const char *pc = ", ";
8 string s1("hello");
9 string s2("world");
10
11 string s3 = s1 + pc + s2 + "/n";
12 cout << "s3 = s1 + pc + s2 + /"//n/" :"
13 << s3;
14 //可以将一个C风格的字符串赋值给一个string对象,但是反向的转换不能自动执行
15 string str;
16 const char *p = "a character array";
17 str = p;
18 cout << str << endl;
19 //char *p1 = str;//这是不合法的赋值。
20 //但是可以显式的调用c_str();
21 const char *p1 = str.c_str(); //因为c_str()返回的是常量数组
22 cout << p1 << endl;
23 return 0;
24 }
编译:$g++ string_C++_C.c
运行:./a.out
结果:
s3 = s1 + pc + s2 + "/n" :hello, world
a character array
a character array
下面是C++中string类型访问单个字符操作的例子:
1 #include<iostream>
2 #include<string>
3 using namespace std;
4 int main()
5 {
6 string str("fa.disney.com");
7 int size = str.size();
8
9 for(int i = 0; i < size; ++i){
10 if( str[i] == '.' )
11 str[i] = '_';
12 }
13 cout << str << endl;
14 return 0;
15 }
编译:$g++ string_char.c
运行:$./a.out
结果:
fa_disney_com
本文介绍了C++中处理字符串的两种方法:C风格字符串与C++标准库中的string类。通过实例展示了如何使用这两种方法进行字符串长度计算、拼接、替换等操作,并探讨了它们之间的互用性。
1884

被折叠的 条评论
为什么被折叠?



