栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ string类常见操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ string类常见操作

1.反转字符串

反转字符串为常见的日常操作,在c++中可以用algorithm里的reverse方法进行操作。

#include
#include
#include
#include
using namespace std;

void func0() {
    string s = "abcde";
    std::reverse(s.begin(), s.end());
    cout<<"s is: "< 

上述方法输出为

s is: edcba
s1 is: abcde
s2 is: edcba

使用reverse方法以后,字符串本身发生了改变。如果需要保留原有字符串,则可以再新创建一个字符串进行反转。

2.插入字符

插入字符可以使用push_back与insert方法。其中,push_back是在字符串尾部操作,而insert可以在字符串任意位置进行操作。

void func1() {
    string s = "abcde";
    s.push_back('f');
    s.insert(s.begin(), '0');
    cout<<"s is: "< 
s is: 0abcdef
3.字符串拼接

append方法可以用来进行字符串拼接,”+“也可以收到同样效果

void func2() {
    string s = "aaa";
    s.append("bbb");
    cout<<"s is: "< 
s is: aaabbb
ss is: aaabcd
4.字符串遍历

遍历可以使用下标,也可以使用迭代器。迭代器可以是正向,也可以是反向。

void func3() {
    string s = "abcd";
    for(int i=0; i 
a b c d 
a b c d 
d c b a 
5.删除字符串中的字符
void func4() {
    string s = "abcdefghigk";
    s.erase(s.begin());
    cout< 
bcdefghigk
efghigk

从上面的例子可以看出,erase方法中的参数,可以使用迭代器,也可以指定索引位置。

6.字符串替换
void func5() {
    string s = "ni hao hello world";
    s.replace(0, 2, "ta");
    cout< 
ta hao hello world
7.删除所有空格
void func6() {
    string str = "ni hao  aaa";
    str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
    cout< 
nihaoaaa
8

注意remove方法与erase方法配合使用。

8.转大小写
void func7() {
    string s = "abcd";
    for(int i=0; i 
s is: ABCD
s is: abcd
9.判断子串起始位置
void func8() {
    string s = "abcdefg";
    int index1 = s.find("abc");
    cout<<"index1 is: "< 
index1 is: 0
index2 is: -1

find方法如果找到子串,返回起始位置。如果没有找到,则返回-1.

10 获取子串
void func9() {
    string s = "abcdefg";
    cout< 
abc

注意substr方法,得到的结果为左闭右开区间。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/976422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号