2.string

string

文章目录

    • string
      • 转换(好用!)
      • 重点
        • 尾接字符串一定要用 `+=`
      • 拼接
      • 函数
        • 查找
        • 替换
        • 比较
        • 子串 (常用)
        • 插入
        • 删除

#include

转换(好用!)

目的 函数
int / long long / float / double / long double string to_string( i )
string int stoi( s )
string long long stoll( s )
string float stof( s )
string double stod( s )
string long double stold( s )

重点

  1. 尾接字符串一定要用 +=

string 的 += 运算符,将会在原字符串原地尾接字符串。而 + 了再 = 赋值,会先生成一个临时变量,在复制给 string

通常字符串长度可以很长,使用 + 字符串很容易就 TLE

// 优化前: 15139ms
string s;
for (int i = 0; i < 5e5; i++)
    s = s + "a";

// 优化后: < 1ms (计时器显示0)
string s;
for (int i = 0; i < 5e5; i++)
    s += "a";

拼接

拼接到字符串末尾

string append(string &str);
string operation +=(string &str); //重载+=符号
string s="123";
s.append("456");//s="123456"
s+="789";//s="123456789";

函数

查找

查找字符串第一次出现的位置(下标),从前往后找

int find(string &str,[int pos]); //从pos位置开始查找,可省略

查找字符串最后一次出现的位置(下标),从后往前找

int rfind(string &str,[int pos]); //从pos位置开始查找,可省略
替换
string replace(int pos,int 	n,string &str); //替换从pos位置开始的n个字符为str
比较
int compare(string &str); //与str字符串比较,小于返回-1,等于返回0,大于返回1
子串 (常用)
string substr(int pos,int n); //返回位置pos开始的n个字符,不会改变原本字符串
插入
string insert(int pos,string &str); //在位置pos插入字符串是str
删除
string erase(int pos,int n); //删除位置pos开始的n个字符

你可能感兴趣的:(STL,c++,算法)