stl_string

string

使用string 必须包含头文件

并添加命名空间std

using namespace std;

1 string对象的创建和获取输入方式

#include<iostream>
#include<string>

int main()
{
	//声明string 变量
    std::string buff;
    //方式一
	std::cin>>buff;
	//方式一
	//getline(std::cin,buff);
	std::cout<<buff<<std::endl;
	return 0;
}

2 string类的成员函数汇总

函数名 功能
构造函数 产生/复制字符串
析构函数 销毁字符串
= 赋值
swap() 交换两个字符串的内容
+=,append(),push_back() 追加字符
insert(pos,const char*) 插入字符
erase(pos,const char*) 删除字符
clear() 移除所有字符
resize() 改变字符数量
replace(pos,n,s) 用字符串s中的n个字符从pos位置开始替换
+ 串联字符串
==,!=,<,<=,>=,compare() 比较字符串
size(),length() 返回字符串数量
max_size() 返回字符的最大可能个数
empty() 判断字符串是否为空
capacity() 返回重新分配之前的字符容量
reserve() 保留内存以存储一定数量的字符
[],at() 存取单一字符
>>,getling() 从stream中读取某值
<< 将值写入stream中
copy() 将内容复制为一个c-string
c_str() 将内容以c-string的形式返回
data() 将内容以字符数组的形式返回
substr() 返回子字符串
find() 查找某子串或字符
begin(),end() 提供正向迭代器支持
rbegin(),rend() 提供逆向迭代器支持
get_allocated() 返回配置器

2.1构造函数

string strs //生成空字符串
string s(str) //生成字符串str的复制品
string s(str, stridx) //将字符串str中始于stridx的部分作为构造函数的初值
string s(str, strbegin, strlen) //将字符串str中始于strbegin、长度为strlen的部分作为字符串初值
string s(cstr) //以C_string类型cstr作为字符串s的初值
string s(cstr,char_len)    //以C_string类型cstr的前char_len个字符串作为字符串s的初值
strings(num, c) //生成一个字符串,包含num个c字符
strings(strs, beg, end)    //以区间[beg, end]内的字符作为字符串s的初值
string str ("12345678");
char ch[ ] = "abcdefgh";
string a; //定义一个空字符串
string str_1 (str); //构造函数,全部复制
string str_2 (str, 2, 5); //构造函数,从字符串str的第2个元素开始,复制5个元素,赋值给str_2
string str_3 (ch, 5); //将字符串ch的前5个元素赋值给str_3
string str_4 (5,'X'); //将 5 个 'X' 组成的字符串 "XXXXX" 赋值给 str_4
string str_5 (str.begin(), str.end()); //复制字符串 str 的所有元素,并赋值给 str_5

//out
12345678

12345678
34567
abcde
XXXXX
12345678

2.2 获取字符串的长度

  • size() 和 length():这两个函数会返回 string 类型对象中的字符个数,且它们的执行效果相同。
  • max_size():max_size() 函数返回 string 类型对象最多包含的字符数,和具体的编译有关,一旦程序使用长度超过 max_size() 的 string 操作,编译器会拋出 length_error 异常。
  • capacity():该函数返回在重新分配内存之前,string 类型对象所能包含的最大字符数,也和编译器有关
#include <iostream>
#include <string>
using namespace std;
int main ()
{
    int size = 0;
    int length = 0;
    unsigned long maxsize = 0;
    int capacity=0;
    string str ("12345678");
    string str_custom;
    str_custom = str;
    str_custom.resize (5);
    size = str_custom.size();
    length = str_custom.length();
    maxsize = str_custom.max_size();
    capacity = str_custom.capacity();
    cout << "size = " << size << endl;
    cout << "length = " << length << endl;
    cout << "maxsize = " << maxsize << endl;
    cout << "capacity = " << capacity << endl;
    str_custom.resize(18);
    str_custom.resize(33);
    capacity = str_custom.capacity();
    cout << "capacity = " << capacity << endl;
    return 0;
}
//out
size = 5
length = 5
maxsize = 4294967295
capacity = 15
capacity = 60

2.3 获取字符串元素[],at()

  • 下标操作符 [] 在使用时不检查索引的有效性,如果下标超出字符的长度范围,会示导致未定义行为。对于常量字符串,使用下标操作符时,字符串的最后字符(即 '')是有效的。对应 string 类型对象(常量型)最后一个字符的下标是有效的,调用返回字符 ''。
  • 函数 at() 在使用时会检查下标是否有效。如果给定的下标超出字符的长度范围,系统会抛出 out_of_range 异常
#include <iostream>
#include <string>
int main()
{
    const std::string cS ("c.biancheng.net");
    std::string s ("abode");
    char temp =0;
    char temp_1 = 0;
    char temp_2 = 0;
    char temp_3 = 0;
    char temp_4 = 0;
    char temp_5 = 0;
    temp = s [2]; //"获取字符 'c'
    temp_1 = s.at(2); //获取字符 'c'
    temp_2 = s [s.length()]; //未定义行为,返回字符'',但Visual C++ 2012执行时未报错
    temp_3 = cS[cS.length()]; //指向字符 ''
    temp_4 = s.at (s.length ()); //程序异常
    temp_5 = cS.at(cS.length ()); //程序异常
    std::cout << temp <<temp_1 << temp_2 << temp_3 << temp_4 << temp_5 << std::endl;
    return 0;
}

2.4 字符串的比较

Basic_string 类模板既提供了 >、<、==、>=、<=、!= 等比较运算符 ,使用ascii码进行比较,且任一个字符串均不能为 NULL,否则程序会异常退出。

compare()函数: 如果相比较的两个子串相同,compare() 函数返回 0, 若字符串 S 按字典顺序要先于 S2,则返回负值;反之,则返回正值。下面举例说明如何使用 string 类的 compare() 函数。

int compare (const basic_string& s) const;//两个字符串完整的比较
int compare (const Ch* p) const;  //字符串和c_string字符串完整的比较
int compare (size_type pos, size_type n, const basic_string& s) const;//和字符串s的pos位置开始的n个字符串开始比较
int compare (size_type pos, size_type n, const basic_string& s,size_type pos2, size_type n2) const;//字符串1从位置pos开始的n个字符和字符串s的pos位置开始的n2个字符比较
int compare (size_type pos, size_type n, const Ch* p, size_type = n,pos) const;//同上
#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string A ("aBcdef");
    string B ("AbcdEf");
    string C ("123456");
    string D ("123dfg");
    //下面是各种比较方法
    int m=A.compare (B); //完整的A和B的比较
    int n=A.compare(2,4,B,2,4); //"cdef"和"cdEf"比较,区分大小写
    int p=A.compare(1,5,B,4,2); //"Bcdef"和"Ef"比较
    int q=C.compare(0,3,D,0,3); //"123"和"123"比较
    cout << "m = " << m << ", n = " << n <<", p = " << p << ", q = " << q << endl;
    return 0;
}
m = 1, n = 1, p = -1, q = 0

2.5字符串内容的修改

assign(),operator=,erase(),交换(swap),插入(insert), append() 函数添加字符 等

assign()函数

使用 assign() 函数可以直接给字符串赋值。该函数既可以将整个字符串赋值给新串,也可以将字符串的子串赋值给新串

basic_string& assign (const E*s); //直接使用字符串赋值
basic_string& assign (const basic_string & str, size_type pos, size_type n);
//将str的子串赋值给调用串
basic_string& assign (const basic_string& str);    //使用字符串的“引用”賦值
basic_string& assign (size_type n, E c) ; //使用 n个重复字符賦值
basic_string& assign (const_iterator first, const_iterator last);    //使用迭代器赋值
swap()函数
void swap (basic_string& str);
string str1("abc"),str2 ("def");
str1.swap (str2);
insert()函数

只是插入,不会覆盖原来的字符串。

//在pos位置插入字符串s
basic_string& insert (size_type pos , const E * s); 
// 在pos位置插入字符串s的前n个字符
basic_string& insert (size_type pos , const E * s, size_type n); 
basic_string& insert (size_type pos, const basic_string& str);
//选取 str 的子串插入pos
basic_string& insert (size_type pos, const basic_string& str,size_type pos, size_type n); 
 //在下标 p0 位置插入  n 个字符 c
basic_string& insert (size_type pos, size_type n, E c);
//在 it 位置插入字符 c
iterator insert (iterator it, E c); 
void insert (iterator it, const_iterator first, const_iterator last); //迭代器的方式插入
void insert (iterator it, size_type n, E c) ; //在 it 位置重复插入 n 个字符 c
append()函数
basic_string& append (const E * s); //在原始字符串后面追加字符串s
basic_string& append (const E * s, size_type n);//在原始字符串后面追加字符串 s 的前 n 个字符
//在原始字符串后面追加字符串 s 的子串 s [ pos,…,pos +n -1]
basic_string& append (const basic_string& str, size_type pos,size_type n);
basic_string& append (const basic_string& str);
basic_string& append (size_type n, E c); //追加 n 个重复字符
basic_string& append (const_iterator first, const_iterator last); //使用迭代器追加
replace()函数
basic_string& replace (size_type p0, size_type n0, const E * s); //使用字符串 s 从源串的位置 P0 处开始替换,n0没有作用
basic_string& replace (size_type p0, size_type n0, const E *s, size_type n); //使用字符串 s 中的 n 个字符,从源串的位置 P0 处开始替换
basic_string& replace (size_type p0, size_type n0, const basic_string& str); //使用字符串 s 中的 n 个字符,从源串的位置 P0 处开始替换
basic_string& replace (size_type p0, size_type n0, const basic_string& str, size_type pos, size_type n); //使用串 str 的子串 str [pos, pos + n-1] 替换源串中的内容,从位置 p0 处开始替换,替换字符 n0 个
basic_string& replace (size_type p0, size_type n0, size_type n, E c); //使用 n 个字符 'c' 替换源串中位置 p0 处开始的 n0 个字符
basic_string& replace (iterator first0, iterator last0, const E * s);//使用迭代器替换,和 1) 用法类似
basic_string& replace (iterator first0, iterator last0, const E * s, size_type n);//和 2) 类似
basic_string& replace (iterator first0, iterator last0, const basic_string& str); //和 3) 类似
basic_string& replace (iterator first0, iterator last0, size_type n, E c); //和 5) 类似
basic_string& replace (iterator first0, iterator last0, const_iterator first, const_iterator last); //使用迭代器替换
#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string var ("abcdefghijklmn");
    const string dest ("1234");
    string dest2 ("567891234");
    var.replace (3,2, dest);
    cout << "1: " << var << endl;//abc1234ghijklmn,2没有作用
    var = "abcdefghijklmn";
    var.replace (3,1, dest.c_str(), 1, 3);//abc234efghijklmn,1没有作用
    cout << "2: " << var << endl;
    var ="abcdefghijklmn";
    var.replace (3, 1, 5, 'x');
    cout << "3: " << var << endl;
    string::iterator itA, itB;
    string::iterator itC, itD;
    itA = var.begin();
    itB = var.end();
    var = "abcdefghijklmn";
    var.replace (itA, itB, dest);
    cout << "4: " << var << endl;
    itA = var.begin ();
    itB = var.end();
    itC = dest2.begin () +1;
    itD = dest2.end ();
    var = "abodefghijklmn";
    var.replace (itA, itB, itC, itD);
    cout << "5: " << var << endl;
    var = "abcdefghijklmn";
    var.replace (3, 1, dest.c_str(), 4); //这种方式会限定字符串替换的最大长度
    cout <<"6: " << var << endl;
    return 0;
}

2.6字符串内容的查找

find()函数和 rfind()//rfind是逆向搜索
size_type find (value_type _Chr, size_type _Off = 0) const;
//find()函数的第1个参数是被搜索的字符、第2个参数是在源串中开始搜索的下标位置
size_type find (const value_type* _Ptr , size_type _Off = 0) const;
//find()函数的第1个参数是被搜索的字符串,第2个参数是在源串中开始搜索的下标位置
size_type find (const value_type* _Ptr, size_type _Off = 0, size_type _Count) const;
//第1个参数是被搜索的字符串,第2个参数是源串中开始搜索的下标,第3个参数是关于第1个参数的字符个数,可能是 _Ptr 的所有字符数,也可能是 _Ptr 的子串宇符个数
size_type find (const basic_string& _Str, size_type _Off = 0) const;
//第1个参数是被搜索的字符串,第2参数是在源串中开始搜索的下标位置
find_first_of()函数和 find_last_of()函数

find_first_of() 函数可实现在源串中搜索某字符串的功能,该函数的返回值是被搜索字符串的第 1 个字符第 1 次出现的下标(位置)。若查找失败,则返回 npos。

find_last_of() 函数同样可实现在源串中搜索某字符串的功能。与 find_first_of() 函数所不同的是,该函数的返回值是被搜索字符串的最后 1 个字符的下标(位置)。若查找失败,则返回 npos。

//从源字符串pos处查找字符ch
size_type find_first_not_of (value_type_Ch, size_type_Off pos = 0) const; size_type 
//从源字符串pos处查找字符串ptr
find_first_of (const value_type* _Ptr, size_type _Off = 0) const;
size_type find_first_of (const value_type* _Ptr, size_type_Off, size_type_Count) const;
size_type find_first_of (const basic_string & _Str, size_type_Off = 0) const;
size_type find_last_of (value_type _Ch, size_type_Off = npos) const;
size_type find_last_of (const value_type* _Ptr, size_type_Off = npos) const;
size_type find_last_of (const value_type* _Ptr, size_type _Off, size_type _Count) const;
size_type find_last_of (const basic_string& _Str, size_type_Off = npos) const;
#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string str_ch ("for");
    string str("Hi, Peter, I'm sick. Please bought some drugs for me. ");
    int length = str.length();
    string::size_type m = str.find_first_of ('P', 0);
    string::size_type rm = str.find_last_of ('P', (length - 1));
    cout << "Example - find_first_of (): The fposition  of 'P' is: " << (int) m << endl;
    cout << "Example - find_last_of (): The lposition  of 'P' is: " << (int) rm << endl;
    string:: size_type n = str.find_first_of ("some", 0);
    string:: size_type rn = str.find_last_of ("some", (length -1));
    cout << "Example - find_first_of(): The fposition of 'some' is: " << (int) n << endl;
    cout << "Example - find_last_of(): The lposition of 'some' is: " << (int) rn << endl;
    string:: size_type mo = str.find_first_of ("drugs", 0, 5);
    string:: size_type rmo = str.find_last_of ("drugs", (length-1), 5);
    cout << "Example - find_first_of () : The fposition of 'drugs' is: " << (int) mo << endl;
    cout << "Example - find_last_of () : The lposition  of 'drugs' is: " << (int) rmo << endl;
    string::size_type no = str.find_first_of (str_ch, 0);
    string::size_type rno = str.find_last_of (str_ch, (length -1));
    cout << "Example - find_first_of() : The position of 'for' is: " << (int) no << endl;
    cout << "Example - find_last_of () : The position of 'for' is: " << (int) rno << endl;
    return 0;
}
Example - find_first_of (): The fposition of 'P' is: 4
Example - find_last_of (): The lposition of 'P' is: 21
Example - find_first_of(): The fposition of 'some' is: 5
Example - find_last_of(): The lposition of 'some' is: 51
Example - find_first_of () : The fposition of 'drugs' is: 8
Example - find_last_of () : The lposition of 'drugs' is: 48
Example - find_first_of() : The position of 'for' is: 8
Example - find_last_of () : The position of 'for' is: 48
find_first_not_of()函数和 find_last_not_of()函数

find_first_not_of() 函数可实现在源字符串中搜索与指定字符(串)不相等的第 1 个字符;find_last_not_of() 函数可实现在源字符串中搜索与指定字符(串)不相等的最后 1 个字符。这两个函数的参数意义和前面几个函数相同,它们的使用方法和前面几个函数也基本相同。

size_type find_first_not_of (value_type _Ch, size_type_Off = 0) const;
size_type find_first_not_of (const value_type * _Ptr, size_type_Off = 0) const;
size_type find_first_not_of (const value_type* _Ptr, size_type_Off, size_type_Count) const;
size_type find_first_not_of (const basic_string & _Str, size_type_Off = 0) const;

2.7 迭代器在string中的应用

STL 定义了 5 种迭代器,根据所需的迭代器类型对算法进行描述。这 5 种迭代器分别是:输入迭代器、输出迭代器、正向迭代器、双向迭代器和随机访问迭代器。对于这 5 种迭代器不仅可以执行解除引用操作(* 操作符),还可进行比较。本节主要讲述 basic_string(或 string 类)中迭代器的使用。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main ()
{
    string s ("The zip code of Hondelage in Germany is 38108.");
    cout << "Original: " << s << endl;
    string sd(s.begin(),s.end ()); //构造函数中使用迭代器
    cout << "Destination: " << sd << endl;
    transform (sd.begin(), sd.end(), sd.begin(), [](unsigned char c){return toupper(c)}); //算法中使用迭代器(仿函数)
    cout << "Destination (All Toupper)): " << sd << endl;
    string sd1;
    sd1.append (sd.begin(),(sd.end() -7)); //append()函数中使用迭代器
    cout << "Destination sd1: " << sd1 << endl;
    string sd2;
    string::reverse_iterator iterA;
    string temp = "0";
    for (iterA = sd.rbegin (); iterA != sd.rend (); iterA++) //reverse_iterator
    {
        temp=* iterA;
        sd2.append (temp);
    }
    cout << "Destination sd2: " << sd2 << endl;
    sd2.erase (0, 15); //erase()函数中使用迭代器
    cout << "Destination sd2 (Erased 15 chars) : " << sd2 << endl;
    //string::iterator iterB = sd2.begin ();
    string sd3 = string ("12345678");
    sd2.insert (sd2.begin(), sd3.begin(), sd3.end()); //insert()函数中使用迭代器
    cout << "Destination sd2 (Insert 8 chars) : " << sd2 << endl;
    sd2.replace (sd2.begin (), sd2.end(), "This is an Exarrple of Replace"); //Replace
    cout <<"Destination sd2 (Replace All): " << sd2 << endl; // replace ()函数中使用迭代器
}

out

Original: The zip code of Hondelage in Germany is 38108.
Destination: The zip code of Hondelage in Germany is 38108.
Destination (All Toupper)): THE ZIP CODE OF HONDELAGE IN GERMANY IS 38108.
Destination sd1: THE ZIP CODE OF HONDELAGE IN GERMANY IS
Destination sd2: .80183 SI YNAMREG NI EGALEDNOH FO EDOC PIZ EHT
Destination sd2 (Erased 15 chars) : EG NI EGALEDNOH FO EDOC PIZ EHT
Destination sd2 (Insert 8 chars) : 12345678EG NI EGALEDNOH FO EDOC PIZ EHT
Destination sd2 (Replace All): This is an Exarrple of Replace
原文地址:https://www.cnblogs.com/Alexkk/p/12442161.html