标准库类型string
表示可变长的字符序列,使用string类型前必须首先包含string头文件
定义和初始化string对象
string a1; //默认初始化
string a2(a1); //a2是a1的副本
string a3=a1; //等价于a3(a1),a3是a1的副本
string a4("hello world"); //a4是字面值"hello world"的副本
string a5="hello world"; //等价于a5("hello world")
string a6(n,'c'); //把a6初始化为由连续n个字符c组成的串
代码演示:
#include<iostream>
using namespace std;
#include<string>
int main()
{
string a1;
string a2(a1);
string a3 = a1;
string a4("hello");
string a5 = "world";
string a6(10, 'a');
cout << a1 << endl;
cout << a2 << endl;
cout << a3 << endl;
cout << a4 << endl;
cout << a5 << endl;
cout << a6 << endl;
system("pause");
return 0;
}
直接初始化和拷贝初始化
- 直接初始化:不使用等号,使用():a("hello")
- 拷贝初始化:使用等号:a=“hello”
string对象上的操作
os<<s; //将s写道输出流os当中,返回os
is>>s; //从is中读取字符串赋给s,字符串以空白1分割,返回is
getline(is,s); //从is中读取一行赋给s,返回is
s.empty() //s为空返回true,否则返回false
s.size(); //返回s中字符的个数
s[n]; //返回s中第n个字符的引用,位置n从0记起
s1+s2; //返回s1和s2连接后的结果
s1=s2 //用s2的副本代替s1中原来的字符
s1==s2 //判断s1和s2是否完全相等
s1!=s2 //判断s1和s2是否不相等
<,<=,>,>= 利用字典中的顺序进行比较
- 读写string对象过程中,string会自动忽略开头的空白(即空格符,换行符,制表符等)并从第一个真正的字符开始读起,直到遇见下一处空白为止,因此当输入的一段字符中如果包含字符的话,则不能完整读取
eg:输入“hello world”;则读取的为hello,而空格后的world则被忽略
此时可以用getline读取。
string的empty和size类型
- empty就正常判断是否为空
- 对于size函数,需要注意其返回类型
size的返回值是一个string::size_type类型的值,他是一个无符号类型的值,而且足够存放下任何string对象的大小。C++11中允许用auto或者decltype来推断变量的类型
auto len =line.size(); //len的类型是string::size_type
由于size函数返回的是一个无符号的整型,假设n是一个负值的int,则len<n的判定几乎可以肯定为true。这是因为负值n会自动转换为一个比较大的无符号值。
注:如果一条表达式中已经有了size()函数就不要使用int了,这样可以避免int和unsugned可能带来的问题
string相加时需要注意的问题
必须确保每个加法运算符(+)的两侧的运算对象至少有一个时string
string a1 = "hello";
string a2=a1+" sdsa"; //正确,一条语句中至少有一个string类型
string a3 = "asda"+"asds" //错误,没有string类型
string a4 = a1+"hello"+"world" //正确
string a5="hello"+"world"+a1; //错误
当有多个加号时,他的工作机理和连续输入连续输出是一样的
a4可以变为a4=(a1+"hello")+"world";
第一个扩号仍然正确
a5可以变为a5=("hello"+"world")+a1;
第一个扩号内无string类型,所以不正确
处理string对象中的字符
isalnum(c) //当c是字母或者数字时为真
isalpha(c) //当c是字母时为真
iscntrl(c) //当c是控制字母时为真
isdigit(c) //当c是数字时为真
isgraph(c) //当c不是空格但可以打印时为真
islower(c) //当c是小写字母时为真
isprint(c) //当c是可打印字符时为真
ispunct(c) //当c是标点符号时为真
isspace(c) //当c是空白时为真
isupper(c) //当c是大写字母时为真
isxdigit(c) //当c是十六进制数字时为真
tolower(c) //如果c是大写字母,输出对应的小写字母;否则原样输出
toupper(c) //如果c是小写字母,输出对应的大写字母;否则原样输出
使用for语句处理string字符串
eg:
#include<iostream>
using namespace std;
#include<string>
int main()
{
string s("c,ds,ac,s sad,as");
int num = 0;
for (auto c : s) //判断有几个标点符号
if (ispunct(c))
++num;
cout << "num:" << num << endl;
for (auto &c : s) //小写变大写
c = toupper(c);
cout << s << endl;
for (decltype(s.size()) i = 0; i != s.size(); ++i) //另一种循环方法,大写变小写
{
s[i] = tolower(s[i]);
}
cout << s << endl;
system("pause");
return 0;
}