C++string类中常用函数

本文介绍了C++标准模板库(STL)中string类的几个关键函数:erase用于删除字符,包括按位置、范围删除等;insert用于在字符串中插入字符或字符串;find函数查找子字符串的位置;substr函数用于提取字符串的子串。示例代码展示了这些函数的使用方法。
摘要由CSDN通过智能技术生成

erase函数

(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符

(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)

(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)

(4)erase(n);删除从n往后的所有字符

例子:

#include <iostream>
#include <string>
using namespace std;
 
int main ()
{
  string str ("This is an example phrase.");
  string::iterator it;
 
  // 第(1)种用法
  str.erase (10,8);
  cout << str << endl;        // "This is an phrase."
 
  // 第(2)种用法
  it=str.begin()+9;
  str.erase (it);
  cout << str << endl;        // "This is a phrase."
 
  // 第(3)种用法
  str.erase (str.begin()+5, str.end()-7);
  cout << str << endl;        // "This phrase."
 
  // 第(4)种用法
  str.erase(4);
  cout << str << endl;        // "This"
  return 0;
}

insert函数

(1)string.insert(pos, str):在字符串string的pos位置插入str字符串。pos可以是整数,也可以是迭代器。

(2)string.insert(pos, n, ch):在字符串string的pos位置插入n个ch字符。

例子:

string str1 = "Hello";
str1.insert(5, " World");
cout<<str1;    // 输出 "Hello World"
string str2 = "Hello";
str2.insert(5, 3, '!');
cout<<str2;    // 输出 "Hello!!!"

find函数

(1)string.find(str):在字符串中查找str,若查到则返回str在string中第一个字符出现的下标,若没有找到则返回string::npos。

(2)string.find(str,pos):在字符串中从pos位置开始查找str,若查到则返回str在string中第一个字符出现的下标,若没有找到则返回string::npos。

#include<iostream>
using namespace std;
int main()
{
    string s;
    cin >> s;
    string s1 = "123";
    int pos = s.find(s1);
    cout << pos;  //string::npos强制转换成整型时会变成-1
    return 0;
}
//在字符串中多次查找指定字串
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int pos=0, ans=0;
    string s1, s2;
    getline(cin, s1);
    getline(cin, s2);
    while ((pos = s2.find(s1, pos)) != string::npos)
    {
        pos++;
        ans++;
    }
    cout << ans;
    return 0;
}

substr函数

(1)string.substr(start,n):从start开始位置截取n个字符。

(2)string.substr(start):从start开始位置截取往后的所有字符。

#include<iostream>
using namespace std;
int main()
{
    string s;
    cin >> s; //helloworld
    string str = s.substr(1);
    string str2 = s.substr(0, 5);
    cout << str << endl << str2;
    return 0;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

另一个人。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值