string
string
size/length
返回string中Char T元素个数
size_type size() const noexcept;
size_type length() const noexcept;
erase
- 用于删除指定位置的数据
iterator erase (iterator p);
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abc";
cout << a << endl;
a.erase(a.begin());
a.erase(-- a.end());
cout << a << endl;
return 0;
}

参数需要的是一个迭代器
- 用于删除string中的从某位置开始的一定长度的数据
string& erase(size_t pos=0, size_t len = npos);
string a = "abc";
a.erase(1, 2);
cout << a << endl;

第二个参数可以省略,表示从当前位置删除到结尾
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abc";
cout << a << endl;
a.erase(1);
cout << a << endl;
return 0;
}
- 删除指定范围的字符
iterator erase (iterator first, iterator last);
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abc";
cout << a << endl;
a.erase(a.begin(), a.begin() + 1);
cout << a << endl;
return 0;
}
区间是左闭右开

需要注意的是erase函数只支持正向迭代器,将反向迭代器作为参数传入时会报错
substr
主要功能是获取string的子串
basic_string substr( size_type pos = 0, size_type count = npos ) const;
参数:
pos:要获取的子串的首个字符的位置count:子串的长度,可以省略,省略则表示从pos到字符串结尾的子串
返回值:
子串:[pos, pos + count)
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abcdefg";
cout << a.substr(1, 5) << endl;
return 0;
}

push_back
功能:插入一个字符到string结尾
void push_back( CharT ch );
pop_back
功能:移除末尾字符等价于erase(end() - 1)
void pop_back();
clear
功能:删除string中的所有字符
void clear() noexcept;
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abcdefg";
cout << a << endl;
a.clear();
cout << a << endl;
return 0;
}

find
- 从pos开始搜索等于str的首个子串
size_type find( const basic_string& str, size_type pos = 0 ) const noexcept;
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abcdefg";
cout << a.find("de") << endl;
return 0;
}

- 寻找从pos开始的首个字符
size_type find( CharT ch, size_type pos = 0 ) const noexcept;
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abcdefg";
cout << a.find('e') << endl;
return 0;
}

如果找不到将返回
npos
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a = "abcdefg";
cout << (a.find('e', 5) == a.npos) << endl;
return 0;
}

data\c_str
data\c_str函数的主要功能是将string转成char数组
(它们几乎是一样的,但最好使用 c_str(),因为 c_str() 保证末尾有空字符,而 data() 则不保证)
printf("%s", s); // 编译错误
printf("%s", s.data()); // 编译通过,但是是 undefined behavior
printf("%s", s.c_str()); // 一定能够正确输出

浙公网安备 33010602011771号