string

string

size/length

返回string中Char T元素个数

size_type size() const noexcept;
size_type length() const noexcept;

erase

  1. 用于删除指定位置的数据
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;
}

image

参数需要的是一个迭代器

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

image

第二个参数可以省略,表示从当前位置删除到结尾

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string a = "abc";
    cout << a << endl;
    a.erase(1);
    cout << a << endl;
    return 0;
}
  1. 删除指定范围的字符
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;
}

区间是左闭右开

image

需要注意的是erase函数只支持正向迭代器,将反向迭代器作为参数传入时会报错

substr

主要功能是获取string的子串

basic_string substr( size_type pos = 0, size_type count = npos ) const;

参数

  1. pos:要获取的子串的首个字符的位置
  2. 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;
}

image

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;
}

image

find

  1. 从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;
}

image

  1. 寻找从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;
}

image

如果找不到将返回npos

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string a = "abcdefg";
    cout << (a.find('e', 5) ==  a.npos) << endl;
    return 0;
}

image

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());  // 一定能够正确输出
posted @   cxy8  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
历史上的今天:
2023-02-03 2023
点击右上角即可分享
微信分享提示