我是靠谱客的博主 炙热手套,这篇文章主要介绍C++ 笔记(09)— 字符串(C 风格字符串、C++字符串 string)1. C 风格字符串2. C++ 风格字符串,现在分享给大家,希望可以做个参考。

C++ 提供了以下两种类型的字符串表示形式:

  • C 风格字符串;
  • C++ 引入的 string 类类型;

1. C 风格字符串

C 风格的字符串起源于 C 语言,并在 C++ 中继续得到支持。字符串实际上是使用 null 字符 终止的一维字符数组。因此,一个以 null 结尾的字符串,包含了组成字符串的字符。

下面的声明和初始化创建了一个 “Hello” 字符串。由于在数组的末尾存储了空字符,所以字符数组的大小比单词 “Hello” 的字符数多一个。

复制代码
1
2
char a[6]={'H', 'e', 'l', 'l', 'o', ''};

依据数组初始化规则,可以把上面的语句写成以下语句:

复制代码
1
2
char a[] = "hello"

请注意,该数组的最后一个字符为空字符 。这也被称为字符串结束字符,因为它告诉编译器,字符串到此结束。这种 C 风格字符串是特殊的字符数组,因为总是在最后一个字符后加上空字符

在代码中使用字符串字面量时,编译器将负责在它后面添加 。在数组中间插入 并不会改变数组的长度,而只会导致将该数组作为输入的字符串处理将到这个位置结束。

其实,不需要把 null 字符放在字符串常量的末尾。 C++ 编译器会在初始化数组时,自动把 放在字符串的末尾。让我们尝试输出上面的字符串:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> using namespace std; int main() { char a[] = {'h','e', 'l', 'l', 'o'}; // 'h' 不能是双引号 cout << "sizeof(a) is " << sizeof(a) << " a is " << a << endl; char b[] = {'h','e', 'l', 'l', 'o', ''}; cout << "sizeof(b) is " << sizeof(b) << " b is " << b << endl; char c[] = {'h','e', '', 'l', 'o', ''}; cout << "sizeof(c) is " << sizeof(c) << " c is " << c << endl; return 0; }

输出:

复制代码
1
2
3
4
sizeof(a) is 5 a is hello sizeof(b) is 6 b is hello sizeof(c) is 6 c is he

使用 C 语言编写的应用程序经常使用 strcpy() 等字符串复制函数、 strcat() 等拼接函数,还经常使用 strlen() 来确定字符串的长度。

这些 C 风格字符串作为输入的函数非常危险,因为它们寻找终止空字符,如果程序员没有在字符数组末尾添加空字符,这些函数将跨越字符数组的边界。

2. C++ 风格字符串

C++ 标准库提供了 string 类类型,支持上述所有的操作,另外还增加了其他更多的功能。无论是处理文本输入,还是执行拼接等字符串操作,使用 C++ 标准字符串都是更高效、更安全的方式。

不同于字符数组(C 风格字符串实现), std::string 是动态的,在需要存储更多数据时其容量将增大。

要使用 C++ 字符串,需要包含头文件 string

复制代码
1
2
#include <string>

使用示例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream> #include <string> using namespace std; int main() { string a = "hello"; string b = "world"; string dst = ""; int len = 0; dst = a; cout << "dst:" << dst << endl; dst = a + b; cout << "dst:" << dst << endl; len = dst.size(); cout << "dst.size :" << len << endl; cout << "dst.length:" << dst.length() << endl; cout << "dst.append(11):" << dst.append("11") << endl; cout << "dst.find('e'):" << dst.find('e') << endl; dst.replace(2, 3, "Z"); // //从位置 2 开始,之后的 3 个字符替换为 "Z", cout << "dst.replace('e', 'Z')" << dst << endl; int first = dst.find_first_of("o"); int last = dst.find_last_of("d"); cout << "first is " << first << endl; cout << "last is " << last << endl; return 0; }

输出结果:

复制代码
1
2
3
4
5
6
7
8
9
10
dst:hello dst:helloworld dst.size :10 dst.length:10 dst.append(11):helloworld11 dst.find('e'):1 dst.replace('e', 'Z')heZworld11 first is 4 last is 7

最后

以上就是炙热手套最近收集整理的关于C++ 笔记(09)— 字符串(C 风格字符串、C++字符串 string)1. C 风格字符串2. C++ 风格字符串的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部