【问题标题】:Can we remove two substrings from a C++ string simultaneously?我们可以同时从 C++ 字符串中删除两个子字符串吗?
【发布时间】:2015-04-14 06:29:36
【问题描述】:

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

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

【问题讨论】:

  • 您可以使用std::regex_match 轻松完成 - 只需捕获要保留在子表达式中的位。
  • 不是"/device""/config"?

标签: c++ string boost


【解决方案1】:

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

但是想想你为什么要这样做。仅仅因为它是一个单一的调用不会让它“很多”更快,因为代码仍然需要以一种或另一种方式执行。

另一方面,为每个单词设置一个命令会提高代码的可读性,这始终应该是高优先级的。

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

【讨论】:

    【解决方案2】:

    算法的具体程度尚不完全清楚。但是,对于给定的情况,以下内容将具有最少的复制并“原子地”进行突变(如:删除两个子字符串或不删除子字符串):

    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
    

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多