String

字符串操作

stl函数方法

  1. 获取字符串长度
    s.size()s.length()

  2. 插入
    s.push_back() 在末尾插入
    s.insert(pos,'c') 在指定位置插入
    s.append(str) 在s字符串结尾添加str字符串

    1
    2
    3
    s.push_back('a')
    s.insert(s.begin(),'1')
    s.append("abc")
  3. 删除
    erase(iterator first, iterator last)
    删除字符串中迭代器区间[first,last)上所有字符

    erase(pos, len)
    删除字符串中从索引位置pos开始的len个字符

  4. 字符替换
    s.replace(pos,n,str) 把当前字符串从索引pos开始的n个字符替换为str
    s.replace(it1,it2,str) 把当前字符串[it1,it2)区间替换为str it1 ,it2为迭代器哦
    tolower(s[i]) \ toupper(s[i]) 转换为小写 \ 大写

  5. 分割
    s.substr(pos,n) 截取从pos索引开始的n个字符

  6. 查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<string>
#include<iostream>
int main() {
string s("dog bird chicken bird cat");
//字符串查找-----找到后返回首字母在字符串中的下标
// 1. 查找一个字符串
cout << s.find("chicken") << endl;// 结果是:9

// 2. 从下标为6开始找字符'i',返回找到的第一个i的下标
cout << s.find('i',6) << endl;// 结果是:11

// 3. 从字符串的末尾开始查找字符串,返回的还是首字母在字符串中的下标
cout << s.rfind("chicken") << endl;// 结果是:9

// 4. 从字符串的末尾开始查找字符
cout << s.rfind('i') << endl;// 结果是:18因为是从末尾开始查找,所以返回第一次找到的字符

// 5. 在该字符串中查找第一个属于字符串s的字符
cout << s.find_first_of("13br98") << endl;// 结果是:4---b

// 6. 在该字符串中查找第一个不属于字符串s的字符------先匹配dog,然后bird匹配不到,所以打印4
cout << s.find_first_not_of("hello dog 2006") << endl; // 结果是:4
cout << s.find_first_not_of("dog bird 2006") << endl; // 结果是:9

// 7. 在该字符串最后中查找第一个属于字符串s的字符
cout << s.find_last_of("13r98") << endl;// 结果是:19

// 8. 在该字符串最后中查找第一个不属于字符串s的字符------先匹配t--a---c,然后空格匹配不到,所以打印21
cout << s.find_last_not_of("teac") << endl;// 结果是:21
}

字符比较

使用 单引号 包括单个字符

1
char c = 's'

字符串变字符数组

1
2
string s = "xing ma qi";
char s2[] = s.c_str();

将数字转换成字符串

to_string(num)

1
2
int a = 12345678;
cout << to_string(a) << '\n';

将字符串变成数字

atoi(const char *)字符数组转换为int类型
stoi(const string*)字符串转换为int类型

关于输出数字的范围:
atoi不做范围检查,如果超出上界,输出上界,超出下界,输出下界。
stoi会做范围检查,默认必须在int范围内,如果超出范围,会出现RE(Runtime Error)错误。

KMP字符串匹配

彻底搞懂 KMP 算法原理


String
https://cs-lb.github.io/2024/04/02/stl/String/
作者
Liu Bo
发布于
2024年4月2日
许可协议