c++ - 有没有办法用循环擦除两个给定的值?
问题描述
如果字符串 sdl1 包含两个值,如“37”,我该如何擦除。考虑到这是两个不同的值 3 和 7。我需要某种列表还是只需要循环?谢谢
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <conio.h>
#include <sstream>
#include <stdio.h>
#include <iterator>
using namespace std;
void eraseAllSubStr(std::string & mainStr, const std::string & toErase)
{
size_t pos = std::string::npos;
while ((pos = mainStr.find(toErase)) != std::string::npos)
{
mainStr.erase(pos, toErase.length());
}
}
int main()
{
std::string str = "123456789";
//Let's Say I want to delete 5 and 8 and string sdl1 = "58".
string sdl1 = "5";
eraseAllSubStr(str, sdl1);
std::cout << str << std::endl;
return 0;
}
最小reprod的输出。例子:
12346789
5 was erased.
But I would like to erase two values like 5 and 8 where string sdl1 = "58"
解决方案
如果我理解您的实际问题:
“如果我想删除像 5 和 8 这样的“58”怎么办?
并且您想在一个循环中同时提供和删除std::string sdl1 = "58";
两者,然后您可以简单地使用std::basic_string::find_first_of来定位其中一个或的位置,然后使用std::basic_string::erase删除字符。唯一的限制是您只想尝试删除字符 while 。5
8
std::string str = "123456789";
5
8
str.find_first_of (sdl1) != std::basic::npos)
一个for
循环是为实现量身定做的,例如:
std::string str = "123456789";
//Let's Say I want to delete 5 and 8 and string sdl1 = "58".
std::string sdl1 = "58";
for (size_t pos = str.find_first_of (sdl1);
pos != std::string::npos;
pos = str.find_first_of (sdl1))
str.erase (pos, 1);
把它放在一个简短的例子中,你可以这样做:
#include <iostream>
#include <string>
int main (void) {
std::string str = "123456789";
//Let's Say I want to delete 5 and 8 and string sdl1 = "58".
std::string sdl1 = "58";
for (size_t pos = str.find_first_of (sdl1);
pos != std::string::npos;
pos = str.find_first_of (sdl1))
str.erase (pos, 1);
std::cout << "str: " << str << '\n';
}
示例使用/输出
$ ./bin/erasechars
str: 1234679
推荐阅读
- reverse-proxy - 通过 ARR 反向代理进行 NTLM 身份验证 - 502.3 错误
- python - 保存 FogBugz 附件时,服务器总是返回空响应(带有一些标头)
- android - Android - 在一个应用程序中设置多个具有不同服务的 Firebase 项目
- android - android微调器对话框弹出背景
- node.js - 服务器端文件系统浏览器
- angular - 如何在 Angular 4 应用程序中使用 Mat-Tree 模块
- r - 延迟计算闪亮与handsontable
- sql - 在 CASE 语句中选择 2 个不同的值
- prestashop - Prestashop 1.7 - 为子主题添加自定义挂钩
- c# - Caliburn Micro MVVM:处理从一个 View/ViewModel 到其他 View/ViewModel 的数据交换