string常用操作 - STEMHA's Blog

string常用操作

基本概念

标准库 string 类型:string 类型支持长度可变的字符串,C++ 标准库将负责管理与存储字符相关的内存,以及提供各种有用的操作。
可以使用输入输出流方式直接进行操作,也可以通过文件等手段进行操作。
size_type是一个依赖于实现的整型,是在string中定义的。
string类将string::npos定义为字符串的最大长度,通常为unsigned int的最大值。
另外,使用缩写NBTS(null-terminated string)来表示以空字符结束的字符串。

头文件

1
#include <string>

模板

1
2
3
//The string class is an instantiation of the basic_string class template, defined in <string> as:
typedef basic_string<char> string;
string实际上是basic_string<char>的一个typedef,同时省略了与内存管理相关的参数。

string初始化方法

1
2
3
4
string s1;	        默认构造函数 s1 为空串
string s2(s1); 将 s2初始化为 s1 的一个副本
string s3(“value”); 将 s3 初始化为一个字符串字面值副本
string s4(n, ‘c’); 将 s4 初始化为字符 ‘c’ 的 n 个副本

注意!因为历史原因以及为了与 C 语言兼容,字符串字面值与标准库 string 类型不是同一种类型。这一点很容易引起混乱,编程时一定要注意区分字符串字面值和 string 数据类型的使用,这很重要。

c-style字符转换

1
s.c_str();	返回指向以null结尾的字符数组的指针,其数据与存储在字符串中的数据相同

交换

swap(string& other):和参数的元素进行交换,所包含对象的类型必须相同。:将当前 string中的元素和参数 string 中的元素交换。它们需要包含相同类型的元素。也可以调用全局函数模板 swap() 来完成同样的操作。

1
2
3
4
void swap(string &x) 重载1:x.swap(y)
void swap (string& x, string& y) 重载2: swap(x, y)
q.swap(p) //交换两个string
所有迭代器和引用都可能无效

常用操作

读写操作

对于string类型变量s的输入:

1
cin >> s;

从标准输入读取 string 并将读入的串存储在 s 中。string 类型的输入操作符:

  • 读取并忽略开头所有的空白字符(如空格,换行符,制表符)。
  • 读取字符直至再次遇到空白字符,读取终止。

读入未知数目的string 对象

1
2
3
4
string word;
程序将从标准输入读取一组 string 对象,然后在标准输出上逐行输出:
while (cin >> word)
cout << word << endl;

上例中,用输入操作符来读取 string 对象。该操作符返回所读的istream 对象,并在读取结束后,作为 while 的判断条件。如果输入流是有效的,即还未到达文件尾且未遇到无效输入,则执行 while 循环体,并将读取到的字符串输出到标准输出。如果到达了文件尾,则跳出 while 循环。

使用getline 读取整行文本

1
2
3
string line; // read line at time until end-of-file
while (getline(cin, line)) //循环读取输入流
cout << line << endl;

赋值

1
2
3
4
// st1 is an empty string, st2 is a copy of the literal
string st1, st2 = "The expense of spirit";
st1 = st2; // replace st1 by a copy of st2
它必须先把 st1 占用的相关内存释放掉,然后再分配给 st2 足够存放 st2 副本的内存空间,最后把 st2 中的所有字符复制到新分配的内存空间。

和字符串字面值的连接

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

1
2
3
4
5
6
7
string s1 = "hello"; // no punctuation
string s2 = "world";
string s3 = s1 + ", "; // ok: adding a string and a literal
string s4 = "hello" + ", "; // error: no string operand s4 的初始化试图将两个字符串字面值相加,因此是非法的
string s5 = s1 + ", " + "world"; // ok: each + has string operand
string s6 = "hello" + ", " + s2; // error: can't add string literals
s6 的初始化是非法的。依次来看每个子表达式,则第一个子表达式试图把两个字符串字面值连接起来。这是不允许的,因此这个语句是错误的。

大小与是否为空

1
2
3
4
5
6
7
8
9
s.empty();	    true如果字符串为空, 否则返回false
s.size(); 字符串中CharT元素的数量
s.length(); 字符串中CharT元素的数量
s.capacity(); 返回字符串当前为其分配空间的字符数
s.max_size(); 返回string对象能够容纳的字符的最大数目
s.resize(size_t n, char c); 用来改变string的大小,如果size小于原来string的size大小,则截取前面的size个字符,如果大于,则用空格填充。
s.resize(size_t n);
s.reserve(size_t res_arg=0);为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserve不会改变容量大小。
s.shrink_to_fit() 请求删除未使用的容量

注意:

  • resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
  • size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。

插入追加覆盖

1
2
3
4
5
s.append(args);	将args追加到s.返回一个指向s的引用.
s.assign(args); 将s中的字符替换为args指定的字符.返回一个指向s的引用.
s.push_back(char c); 在末尾添加一个元素,返回值为空
string& insert ( size_t pos1, size_t n, char c ); 在字符串pos1位置,插入n次c字符。
size_t copy ( char* s, size_t n, size_t pos = 0) const; 从pos位置开始,复制n个字符到s指针指向的内存;

insert

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  string str="to be question";
string str2="the ";
string str3="or not to be";
string::iterator it;
// used in the same order as described above:
str.insert(6,str2); // to be (the )question
str.insert(6,str3,3,4); // to be (not )the question
str.insert(10,"that is cool",8); // to be not (that is )the question
str.insert(10,"to be "); // to be not (to be )that is the question
str.insert(15,1,':'); // to be not to be(:) that is the question
it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...)
str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
Output:to be, or not to be: that is the question...

append()

1
2
3
4
5
6
7
8
9
10
11
12
  string str;
string str2="Writing ";
string str3="print 10 and then 5 more";

str.append(str2); // "Writing "
str.append(str3,6,3); // "10 "
str.append("dots are cool",5); // "dots "
str.append("here: "); // "here: "
str.append(10,'.'); // ".........."
str.append(str3.begin()+8,str3.end()); // " and then 5 more"
str.append<int>(5,0x2E); // "....."
Output: Writing 10 dots here: .......... and then 5 more.....

查找

1
2
3
4
5
s[index]; 
s.at(index); index是下标
size_t find (char c, size_t pos =0) const; 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
size_t rfind(char c, size_t pos = npos); 反向查找,从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
string substr(size_t pos = 0, size_t n= npos)const; 在str中从pos位置开始,截取n个字符,然后将其返回

删除与清空

1
2
3
4
5
s.clear()	从字符串中删除所有字符, clear()只是将string中有效字符清空,不改变底层空间大小。
s.erase(pos,len); 删除从位置pos开始的len个字符,如果len被省略,则删除从pos开始直至s末尾的所有字符.返回一个指向s的引用.
iterator erase (const_iterator p); 删除源字符串中迭代器p指向的字符,返回删除后迭代器的位置。
iterator erase (const_iterator first, const_iterator last); 删除源字符串迭代器范围为[first,last)内的所有字符,返回删除后迭代器的位置。
s.pop_back(); 删除源字符串的最后一个字符,有效的减少它的长度。

数值转换为string

1
2
3
4
5
6
7
8
9
10
11
s=std::to_string(int/double/...);

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

迭代器与指针

1
2
3
4
5
6
7
8
s.data();	返回指向字符串第一个字符的指针
s.begin(); 返回字符串第一个字符的迭代器,const
s.cbegin(); 返回字符串第一个字符的迭代器
s.end(); 返回字符串最后一个字符的后面一个位置的迭代器
s.cend(); 返回字符串最后一个字符的后面一个位置的迭代器,const
s.rbegin(); 反向迭代器
s.rend(); 反向迭代器
string::npos 相当于s.end()

string 对象中字符的处理

我们经常要对 string 对象中的单个字符进行处理,例如,通常需要知道某个特殊字符是否为空白字符、字母或数字。下表列出了各种字符操作函数,适用于 string 对象的字符(或其他任何 char 值)。这些函数都在 cctype 头文件中定义。
注意这里的”cctype”就是C++中使用C标准的头文件的写法,等价于”ctype.h”

操作 功能描述
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。
isspace( c ) 如果 c 是空白字符,则为 true。
isupper( c ) 如果 c 是大写字母,则 true。
isxdigit( c ) 如果是 c 十六进制数,则为 true。
tolower( c ) 如果 c 大写字母,返回其小写字母形式,否则直接返回 c。
toupper( c ) 如果 c 是小写字母,则返回其大写字母形式,否则直接返回 c。
列出了各种字符操作函数
表中的大部分函数是测试一个给定的字符是否符合条件,并返回一个 int 作为真值。如果测试失败,则该函数返回 0 ,否则返回一个(无意义的)非 0 ,表示被测字符符合条件

参考资料

《C++Primer》第三章-标准库类型-学习笔记(1)-string&vector&迭代器
C++ STL丨string 基本使用(一)
STL string常用操作指令
C++——string类和标准模板库
【C++】String类、String类的常用接口说明及其使用、STL中的迭代器使用
c/c++ reference

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×