string

字符串的处理一直都是一个麻烦的事情。c++专门提供了string容器来处理字符串问题。

string类型的初始化

  • string s1 // 默认初始化
  • string s2(s1) // 直接初始化
  • string s2 = s1 // 拷贝初始化
  • string s(cp, n) // 从cp指向的数组中拷贝前n个字符
  • string s(s2, pos2) // 从s2的pos2位置开始拷贝
  • string s(s2, pos2, len2) // 从从s2的pos2位置开始拷贝len2个字符

string类型的基础操作

  • getline(is, s) // 从is读入一整行
  • empty()
  • size()
  • 下标操作
  • operator+ // 连接操作
  • operator= // 赋值
  • == // 判断相等
  • < <= >= > // 字典序比较

对于单字符,定义了如下的一些操作

  • isalnum // 是否为字母或数字
  • isalpha // 是否为字母
  • iscntrl // 是否为控制字符
  • isdigit // 是否为数字
  • isgraph // 不是空格且可打印的字符
  • islower // 小写字母
  • isspace // 空格
  • isupper // 大写字母
  • isxdigit // 十六进制数字
  • tolower // 输出转换后的小写字母
  • toupper // 输出转换后的大写字母

substr

substr会将原字符进行截取部分字符,拷贝给新的字符串

1
s.substr(pos, n)    // 从pos开始,拷贝n个字符

插入和删除

由于string也是顺序容器的一种,因此顺序容器的方法,都可以用于string,如下:

  • insert
  • erase
  • empty
  • size

同时,string还定义了自己的两个函数

  • append // 在尾部插入字符或者字符串
  • replace(pos, len, args) // 从pos开始,将len个长度的字符替换为args中的字符

查找

  • s.find(args)
  • s.rfind(args)
  • s.find_first_of(args)
  • s.find_last_of(args)
  • s.find_first_not_of(args)
  • s.find_last_not_of(args)

args的格式为:

  • c, pos // 从s的pos位置开始查找c
  • s2, pos // 从s的pos位置开始查找s2
  • cp, pos // 从s的pos位置开始查找cp指向的字符串
  • cp, pos, n // 从s的pos位置开始查找cp指向的字符串的前n个字符

比较操作

  • compare
  • 关系运算符

数值转换

  • to_string
  • stoi
  • stol
  • stof
  • stoll
  • stod

string流

sstream头文件中定义了可以直接从输入输出流中转换为string对象的操作,其中istringstream从string读取数据,ostringstream向string写入数据

以下面的例子为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
TextQuery::TextQuery(istream& is)
{
string text;
while (getline(is, text)) { // getline从is中读取整行的数据作为string
file.push_back(text);
int n = file.size() - 1;
istringstream line(text); // 利用string构造istringstream
string word;
while(line >> word) { // 利用while循环将istringstream切分为每个单词
wm[word].insert(n);
}
}
}
显示 Gitment 评论