string的查找和替换

1、替换字符串s1中的s2.

//把字符串中的“、”替换为123. 
#include <iostream>
using namespace std;
#include "string"
#include "algorithm"

void main()
{
    string s1 = "STL可分为容器(containers)、迭代器(iterators)、空间配置器(allocator)、配接器(adapters)、算法(algorithms)、仿函数(functors)六个部分";
    string s2 = "、";
    int len = s2.length(); 
    cout << len << endl;
    cout << s1<< endl;
    int off = 0;
    off = s1.find(s2, 0);
    while (off != string:: npos)
    {
    //  s1.erase(off, len);
        s1.replace(off, len ,"123");
        off = s1.find(s2, off + 1);
    }
    cout << "s1替换后的结果: " << s1 << endl;

    system("pause");
}

这里写图片描述

2、去除字符串中的括号

#include <iostream>
using namespace std;
#include "string"
#include "algorithm"

void main()
{
    string s1 = "STL可分为容器(containers)、迭代器(iterators)、空间配置器(allocator)、配接器(adapters)、算法(algorithms)、仿函数(functors)六个部分";
    string s2 = "(";
    string s3 = ")";
    int len = s2.length(); 
    cout << len << endl;
    cout << s1<< endl;
    int off = 0;
    off = s1.find(s2, 0);
    while (off != string:: npos)
    {
        s1.erase(off, len);
        //s1.replace(off, len ,"123");
        off = s1.find(s2, off + 1);
    }
    off = s1.find(s3, 0);
    while (off != string::npos)
    {
        s1.erase(off, len);
        //s1.replace(off, len ,"123");
        off = s1.find(s3, off + 1);
    }
    cout << "\ns1替换后的结果: " << s1 << endl;

    system("pause");
}

这里写图片描述

3.小写字母替换为大写

#include <iostream>
using namespace std;
#include "string"
#include "algorithm"

void main()
{
    string s1 = "STL可分为容器(containers)、迭代器(iterators)、空间配置器(allocator)、配接器(adapters)、算法(algorithms)、仿函数(functors)六个部分";
    //string s2 = "(";
//  string s3 = ")";
//  int len = s2.length(); 
//  cout << len << endl;
    cout << "s1: " << s1 << endl;
    transform(s1.begin(), s1.end(), s1.begin(), toupper);


    cout << "\ns1替换后的结果: " << s1 << endl;

    system("pause");
}

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值