我们可以同时从 C++ 字符串中删除两个子字符串吗?

Can we remove two substrings from a C++ string simultaneously?

假设我有一个 C++ 字符串 /dev/class/xyz1/device/vendor/config。作为我工作的一部分,我需要从上面的字符串中删除子字符串 "device""config"

我知道我可以通过使用 "erase" 调用两次来完成它。但是,我想知道这是否可以在一次调用中实现。任何字符串 class 库调用或提升调用来实现此目的?

除了正则表达式,我不知道任何其他方法。

不过想想你为什么要这样做。仅仅因为它是单个调用不会使它 "alot" 更快,因为代码仍然需要以一种或另一种方式执行。

另一方面,每个单词都有一个命令会增加代码的可读性,这始终应该是高优先级的。

如果您经常需要这个并且想节省行数,您可以轻松地自己编写这样一个函数,并将其放入您的自定义实用程序函数库中。该函数可以采用输入字符串和 std::vector 字符串或任何其他形式的字符串集合以从先前的字符串中删除。

目前还不完全清楚算法应该有多具体。但是,对于给定的情况,以下将进行最少的复制并进行突变 "atomically" (如:删除两个或不删除子字符串):

namespace ba = boost::algorithm;

void mutate(std::string& the_string) {
    if (ba::ends_with(the_string, "/config")) {
        auto pos = the_string.find("/device/");
        if (std::string::npos != pos) {
            the_string.resize(the_string.size() - 7); // cut `/config`
            the_string.erase(pos, 7);                 // cut `/device`
        }
    }
}

看到了Live On Coliru

#include <boost/algorithm/string.hpp>

namespace ba = boost::algorithm;

void mutate(std::string& the_string) {
    if (ba::ends_with(the_string, "/config")) {
        auto pos = the_string.find("/device/");
        if (std::string::npos != pos) {
            the_string.resize(the_string.size() - 7); // cut `/config`
            the_string.erase(pos, 7);                 // cut `/device`
        }
    }
}

#include <iostream>

int main() {
    std::string s = "/dev/class/xyz1/device/vendor/config";
    std::cout << "before:  " << s << "\n";
    mutate(s);
    std::cout << "mutated: " << s << "\n";
}

版画

before:  /dev/class/xyz1/device/vendor/config
mutated: /dev/class/xyz1/vendor