如何从字符串中删除所有子字符串 [英] How to remove all substrings from a string

查看:204
本文介绍了如何从字符串中删除所有子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从字符串中删除模式的所有实例?

How to remove all instances of the pattern from a string?

string str = "red tuna, blue tuna, black tuna, one tuna";
string pattern = "tuna";


推荐答案

字符串

#include <string>
#include <iostream>

using namespace std;

void removeSubstrs(string& s, string& p) { 
  string::size_type n = p.length();
  for (string::size_type i = s.find(p);
      i != string::npos;
      i = s.find(p))
      s.erase(i, n);
}

int main() {

  string str = "red tuna, blue tuna, black tuna, one tuna";
  string pattern = "tuna";

  removeSubstrs(str, pattern);
  cout << str << endl;
}

这篇关于如何从字符串中删除所有子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆