string类型支持长度可变的字符串,C++标准库将负责管理与存储字符相关的内存,以及提供各种有用对的操作。标准库string类型的目的就是满足对字符串的一般应用。
1.string对象的定义和初始化
通过string类的构造函数来进行初始化。
常用的有:
//默认构造函数,s1为空串
string s1;
//将s2初始化s1的一个副本
string s2(s1);
//将s3初始化为一个字符串字面值副本
string s3("value");
//将s4初始化为字符'c'的n个副本
string s4(4,'c');
在C++11中定义:
|
default (1) |
string(); |
|
copy (2) |
string (const string& str); |
|
substring (3) |
string (const string& str, size_t pos, size_t len = npos); |
|
from c-string (4) |
string (const char* s); |
|
from buffer (5) |
string (const char* s, size_t n); |
|
fill (6) |
string (size_t n, char c); |
|
range (7) |
template <class InputIterator> string (InputIterator first, InputIterator last); |
|
initializer list (8) |
string (initializer_list<char> il); |
|
move (9) |
string (string&& str) noexcept; |
2.string对象的读写
读取并忽略开头所有的空白字符,包括空格,换行符,制表符等
读取字符直至再次遇到空白字符
例如,输入的是 “ this string class ” 则读取的字符串为 “string”
//初始化一个空的string string s; //读取s值 cin >> s; //输出s值 cout << s << endl;
3.string对象的常用操作
|
string类型的常用操作 |
|
|
S.empty() |
如果S为空串,则返回true,否则返回false |
|
S.size() |
返回S中字符的个数 |
|
S[n] |
返回S中位置为n的字符,位置从0开始计数 |
|
S1 + S2 |
把S1 和 S2连接成一个新字符串,返回新生成的字符串 |
|
S1 = S2 |
把S1内容替换为S2的副本 |
|
S1 == S2 |
比较S1和S2的内容,相等则返回true,否则返回false |
|
!=,<,<=,>,>= |
保持这些操作惯有的含义 |
注:size()操作返回的是string::size_type类型的值。string类类型和许多其他库类型都定义了一些配套类型。通过这些配套类型,库类型的使用就能与机器无关。size_type就是这些配套类型中的一种。它定义为与unsigned型具有相同的含义,而且可以保证足够大能够存储任意string对象的长度。为了使用由string类型定义的size_type类型,程序员必须加上作用域操作符来说明所使用的size_type类型是由string类定义的。
保存一个string对象size的最安全的方法就是使用标准库类型 string::size_type 。
从string对象获取字符
string类型通过下标操作符([])来访问string对象中的单个字符。下标操作符需要取一个size_type类型的值,来说明要访问字符的位置。这个下标中的值通常被称为“下标”或“索引”。
/*
* string class practice
* date : 2015--05--19
* @author: zhang
* version: 0.1
* compiled by g++
*/
#include <string>
#include <iostream>
using namespace std;
int main()
{
//默认构造函数,s1为空串
string s1;
//将s2初始化s1的一个副本
string s2(s1);
//将s3初始化为一个字符串字面值副本
string s3("value");
//将s4初始化为字符'c'的n个副本
string s4(4,'c');
//初始化一个空的string
string s;
//读取s值
cin >> s;
//输出s值
cout << s << endl;
//size()和empty()使用例子
string S("this");
cout << "the size of "<< S << " is " << S.size() <<endl;
if(S.empty())
{
cout << "this string is empty " << endl;
}
else
{
cout << "this string is not empty " << endl;
}
//当进行string对象和字符串字面值混合连接操作时,
//+操作符的左右操作符必须至少有一个是string类型的。
string S1 = "string";
//正确
string S2 = S1 + "two";
//错误
//string s3 = "stirng" + "three";
//[]和string::size_type的使用
string str("some string");
for (string::size_type ix = 0; ix != str.size(); ++ ix)
{
cout << str[ix] << endl;
}
return 0;
}
参考文献:
http://www.cplusplus.com/reference/string/string/string/
C++ Primer
原文:http://blog.csdn.net/xinxing__8185/article/details/45848871