STL–第二章 pair[x,y]

支持比较操作符>,>=,<,<=,==,!=

头文件

#include <string>

初始化

string a = "ac";

substr()求子串时常用

#include<iostream> 
#include<string>
using namespace std;

int main () {
   
    string a = "ac";
    a += "w";//支持比较操作符>,>=,<,<=,==,!=
    cout << a << endl; //输出 :acw

    a += "ing";  
    cout << a << endl; //输出:acwing
    //以字符串数组理解
    cout << a.substr(0, 3) << endl; //当第一个数是0 则后一位数:输出从头开始的长度为3的子串acw
    cout << a.substr(1, 3) << endl; //当第一个数是1 则输出下标为1 到下标为3的子串cwi
    cout << a.substr(0, 9) << endl;//如果超出长度范围 则输出原子串acwing
    cout << a.substr(1) << endl; //从下标为1开始输出cwing
    cout << a.substr(0) << endl; //原子串acwing
    printf("%s\n", a.c_str());//如果用printf输出 

    return 0;
}

c_str函数

const char *c_str();

c_str()函数是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string对象转换成c中的字符串样式。

c_str()函数的返回值是const char*类型的,不能直接赋值给一个char *类型的变量,所以就需要我们进行相应的操作转化(利用strcpy函数)

char c[20];
string s = "1234";
strcpy(c,s.c_str());

strcpy函数:

char*strcpy(char*dest,const char*src) //将src复制到dest字符数组中 
头 文 件:#include <string.h> 
返 回 值:char* 类型

push_back()和insert()

string str;
//尾插一个字符
str.push_back('a');
//insert(pos,char)在指定的位置pos前插入字符char
str.insert(a.begin(),'1');//输出1a
//插入字符串
string str2 = "hello";
string s2 = "weakhaha";
str2.insert(0,s2,1,3);
//将字符串s2从下标为1的e开始数3个字符,分别是eak,插入原串的下标为0的字符h前,此时str2="eakhello"

empty()

判断字符串是否为空,空则返回true,非空则返回false

size(),length()

都是返回字母个数

== 注意:length()方法的返回值类型为unsigned类型 ==

clear()

把字符串清空