
1.10 玩转字符串——不一样的风格
字符串指存储在内存的连续字节中的一系列字符。C++中的字符串分为两种形式:C-风格字符串、C++ string类字符串。
1. C-风格字符串
C-风格字符串的头文件为#include<cstring>,默认以'\0'结束,在存储空间中不要忘了'\0'。字符串定义形式如下。
• 字符数组:char a[8]={'v','e','r','y','g','o','o','d'}。
• 字符串:char a[8]={'a','b','c','d','e','f','g','\0'}。
还有另外一种字符串定义。
• 字符串:char a[8]="abcdefg"。
• 字符串:char a[]="afsdjkl;sd"。
字符数组或字符串的长度测量函数为sizeof、strlen。
(1)sizeof:返回所占总空间的字节数,针对整型或字符型数组及整型或字符型指针。由于在编译时计算,因此sizeof不能用来返回动态分配的内存空间大小。
(2)strlen:返回字符数组或字符串所占的字节数,针对字符数组及字符指针。
训练1-43:定义一些字符串,求长度并运算、输出。

C-风格字符串的输入方式有cin、getline和get。
• cin:使用空格、制表符、换行符来确定字符串的结束位置,因此字符串只能接收一个单词。换行符被保留在输入序列中。
• getline:读取一行,直到遇到换行符,丢弃换行符。
• get:读取一行,直到遇到换行符,换行符被保留在输入序列中。
注意!使用cin和get后会将换行符保留在输入序列中,解决方法为再调用一次cin.get。

2. C++ string类字符串
C++ string类字符串的长度没有限制,其头文件为#include<string>。C++中的string类隐藏了字符串的数组性质,使用户可以像处理普通变量一样处理字符串。

注意:
• 可以使用C-风格字符串初始化string类字符串;
• 可以使用cin输入并将输入的内容存储到string类字符串中;
• 可以使用cout输出string类字符串;
• string类字符串没有'\0'的概念;
• char数组使用了一组用于存储一个字符串的存储单元,而string变量使用了一个表示字符串的实体。
字符串的长度测量函数有.length、.size。例如,str.length()和str.size()都可用于求str字符串的长度。

C++string类字符串的输入方式有cin和getline。

训练1-45:输入一些字符串,对其进行复制、拼接、比较等操作。


训练1-46:输入一行字符,统计单词的个数,单词之间以空格隔开。


训练1-47:输入3个字符串,找出其中最小的字符串。
