---
title: "标准库string类型"
author: "Conviction"
date: "2014-09-25T15:57:39Z"
tags: []
categories: ["编程语言"]
slug: "string"
draft: false
lastmod: "2014-09-29T11:05:20Z"
id: 2121644
url: "https://fovj.iteye.com/blog/2121644"
---

string类型支持长度可变的字符串。

#include &lt;string&gt;

using std::string;

 

1.string对象的定义和初始化

（1）string s1;                           默认构造函数，s1为空串

（2）string s2(s1);                     将s2初始化为s1的一个副本

（3）string s3("value");              将s3初始化为一个字符串字面值副本

（4）string s4(n,'c');                   将s4初始化为字符'c'的n个副本

注意：字符串字面值和标准库string类型不是同一种类型。

 

2.string对象的读写

```
#include <iostream>
#include <string>
using std::string;
using std::cin;
int main()
{
	string s;
	cin>>s;
	std::cout<<s;
	return 0;
}
```

 cin&gt;&gt;s：读取并忽略开头所有的空白字符、读取字符直到再次遇到空白字符，读取终止。

 

3.读入未知数目的string对象

```
string world;
while(cin>>world)
{
	cout<<world<<endl;
}
```

4.用getline读取整行文本

```
string world;
while(getline(cin,world))
{
	cout<<world<<endl;
}
```

 5.string对象的操作之size和empty操作

```
string st("Hello World\n");
cout<<"The size of "<<st<<"is "<<st.size()
	<<" character, including the newline"<<endl;
```

 了解st是否为空，一种方法是将size与0进行比较if(st.size() == 0)...。

可以直接换成：

```
if(st.empty()){//...}
```

 注意：st.size()返回值是string::size\_type类型，任何存储string的size操作结果的变量必须为string::size\_type类型。特别的重要，不要把size的返回值赋给一个int变量。因为这是最安全的方法。

 

6.string的关系操作符==、!=、&lt;、&lt;=、&gt;、&gt;=

注意：string对象的比较操作时区分大小写的，即同一个字符的大小写形式被认为是两个不同的字符。在大多数计算机上，大写的字母位于小写的字母之前：任何一个大写字母都小于任意的小写字母。

 

7.string对象的相加

string对象的相加被定义为连接。

```
string st1("Hello");
string st2("World\n");
string st3 = st1 + st2;
cout<<st3<<endl;
```

8.string对象和字符串字面值的连接

注意：当进行string对象和字符串字面值混合连接操作时，+操作符的左右操作数必须至少有一个是string类型的。

```
string s1("hello");
string s2("world");
string s3 = s1 + "," + s2 + "\n";
cout<<s3<<endl;
string ss1 = "hello";
string ss2 = "world";
string ss3 = s1+",";
string ss4 = "hello" + ",";//错误
string ss5 = s1 + "," + "world";
string ss6 = "hello" + "," + s2;//错误
```

 9.从string对象获取字符

string类型通过下标操作符(\[])来访问string对象中的单个字符。下标操作符需要取一个size\_type类型的值，来标明要访问的字符的位置，这个下标通常被称为“下标”或“索引(index)”

注意：string对象的下标从0开始，如果s是一个string对象且s不为空，则s\[0]就是字符串的第一个字符，s\[s.size()-1]则表示s的最后一个字符。

```
string s("some string");
cout<<s.size()<<endl;
for(string::size_type ix = 0; ix!=s.size();++ix)
	cout<<s[ix]<<endl;
```

 

 10.下标错做可用作左值

```
string s("some string");
cout<<s.size()<<endl;
for(string::size_type ix = 0; ix!=s.size();++ix)
	s[ix]='*';
```

 11.下标值

任何可以产生整型值的表达式都可以用作下标操作符的索引。

虽然任何整型值都可作为索引，但索引的实际数据类型却是unsigned类型string::size\_type。

```
string s("some string");
cout<<s.size()<<endl;
for(string::size_type ix = 0; ix!=s.size();++ix)
	s[ix]='*';
int a=1;
int b=2;
s[a+b] = '%';
cout<<s<<endl;
```

 注意：string对象的索引变量最好也用string::size\_type类型。