0、都已包含响应库函数并已进行using声明。
1、string初始化
string s1; //默认构造函数,s1为空字符串
string s2(s1); //将s2初始化为s1的一个副本
string s3("value"); //将s3初始化为一个字符串字面值副本
string s4(n,'c'); //将s4初始化为字符‘c’的n个副本
警告:字符串字面值与标准库string类型不是同一种类型。
2、string对象的读写
-
读取并忽略开头所有的空白字符(如空格,换行符,制表符)。
-
读取字符直至再次遇到空白字符,读取终止。
2.1 读取未知数目的string对象
int main()
{
string word;
while(cin>>word)
cout<<word<<endl;
return 0;
}
当键入Ctrl-z时,跳出读取循环。
2.2 用getline读取正行文本
这个函数接受两个参数:一个输入流对象和一个string对象。读取输入流到换行符的位置,将之前的读取的内容保存到string对象中。
string line;
getline(cin,line);
3、string的对象操作
3.1 size和empty操作
size函数返回string中字符的个数,包含换行符。empty函数返回为bool值,如果对象为空则返回true,否则返回false。
string st("value\n");
cout<<st.size()<<endl; //size = 6
3.2 string::size_type类型
string对象中返回的一种配套类型,本质一般是unsigned。但是为了与硬件无关,设置了这个类型。值得注意的是,相关操作必须是这个类型,特别重要的是,一定不要使用int类型。
3.3 关系操作符
关系操作符==,<,<=,>,>=分别用来测试对象是否相等,小于(等于),大于(等于)。返回值是bool值。
-
比较的是字符的ASCII码。
-
相等是长度和内容都相同。
-
如果长度不同,但是短的和长的前部分匹配,则短的小于长的。
-
如果两个string对象的字符不同,则比较第一个不匹配的字符。
string s1="hello";
string s2="hello world";
string s3="Hello";
string s4="hiya";
//s3<s1<s2<s4
3.4 赋值,相加(连接)
但要注意的是两个字符串字面值不能相加(连接)。
string s1="hello";
string s2="world";
string s3=s1+" "+s2; //ok,"hello world"
string s4="hello"+" "+s2; //error.两个字符串字面值不能相加
string s5=s1+" "+"world"; //ok
3.5 从string对象中获取字符
通常使用下标或索引。下标操作符是一个size_type类型的值。并且可用作左值。
string st("value");
cout<<st[0]<<endl; //ok
cout<<st[5]<<endl; //error
st[1]='*'; //ok,a->*
3.6 string对象中字符的处理
在cctype头文件中定义了很多函数。可以对string对象中的单个字符进行处理。
isalnum(c) //如果c是字母或数字,则为true.
isalpha(c) //如果c是字母,则为true.
iscntrl(c) //如果c是控制字符,则为true.
isdigit(c) //如果c是数字,则为true.
isgraph(c) //如果c不是空格,但可打印,则为true.
islower(c) //如果c是小写字母,则为true.
isprint(c) //如果c是可打印的字符,则为true.
ispunct(c) //如果c是标点符号,则为true.
ispace(c) //如果c是空白字符,则为true.
isupper(c) //如果c是大写字母,则为true.
isxdigit(c) //如果c是十六进制数,则为true.
tolower(c) //如果c是大写字母,则返回其小写字母形式,否则直接返回c.
toupper(c) //如果c是小写字母,则返回其大写字母形式,否则直接返回c.