C++中的字符串类型
来源:互联网 发布:淘宝桌面快捷方式 编辑:程序博客网 时间:2024/05/29 12:05
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++、MFC 中的“字符串”类型介绍
- c语言中的字符类型指针赋值字符串常量
- C风格类型的字符串在C++中的应用
- C++中的字符串类型
- C++中的字符串类型
- C++中的字符串类型
- python中的字符串类型
- C++中的字符串类型
- python中的字符串类型
- C++_字符串类型
- C中的_Bool类型
- C语言中的类型
- C中的字符类型
- C中的布尔类型
- c++中的字符串类型变量
- C++字符串(C类型)
- C风格字符串的类型
- C风格字符串&string类型
- 英美文学资料总结
- 今年流行应用
- Hadoop优化学习
- 同步异步 阻塞非阻塞
- 英美文学资料2
- C++中的字符串类型
- linux nfs mysql struts hibernate spring开发 运维 调优 总结
- MFC改变static text颜色
- 怎样看懂Oracle的执行计划
- Base64编码
- Windows Azure 1.3 新特性-Start-Up 任务
- 进制之间的转换
- HashSet 重写类的equals方法可以根据类的关键字段判断是否相等
- undefined reference to `sin'