首页 > 解决方案 > 有没有办法用循环擦除两个给定的值?

问题描述

如果字符串 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"

标签: c++

解决方案


如果我理解您的实际问题:

“如果我想删除像 5 和 8 这样的“58”怎么办?

并且您想在一个循环中同时提供和删除std::string sdl1 = "58";两者,然后您可以简单地使用std::basic_string::find_first_of来定位其中一个或的位置,然后使用std::basic_string::erase删除字符。唯一的限制是您只想尝试删除字符 while 。58std::string str = "123456789";58str.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

推荐阅读