【问题标题】:How to delete all occurrences of a specific string a string? [duplicate]如何删除所有出现的特定字符串一个字符串? [复制]
【发布时间】:2018-06-04 17:38:32
【问题描述】:

例如,如何删除字符串s = FOOTHEFOOFOOBEST 中所有出现的FOO,这样输出将是THE BEST,不像我的代码那样没有任何额外的空格。
这是我的尝试示例:

#include <iostream>
#include <string>
int main() {

    std::string s = "FOOTHEFOOFOOBEST";
        for (int i = 0; i < s.size(); i++){
            if (s[i] == 'F'&&s[i + 1] == 'O' && s[i + 2] == 'O'){
                std::cout << ' ';
                i += 2;
            }
            else
                std::cout << s[i];
        }

        return 0;
}

我的代码的输出是THE BEST 有一个额外的空间但是我期望THE BEST,有没有更简单的方法来做到这一点?

【问题讨论】:

  • 循环执行std::sring::find(),直到它返回npos
  • 你能用regex吗?
  • 请注意您的代码有 UB,因为您可能会越界访问
  • 中间有两个FOOs,所以两个空格。您还应该注意i + 1i + 2 不会大于size()
  • 尽管此代码中存在未定义的行为(您在搜索循环的尾部违反了分配的大小),但请跟踪您是否有连续替换并且在发生时不要转储空间.该跟踪状态在您进行替换时设置,并在您进入 else-case 时清除。

标签: c++ string


【解决方案1】:

我想我会这样做:

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

template<class Haystack, class Needle, class OutputIterator>
void separate(Haystack&& haystack, Needle&& needle, OutputIterator output_iter)
{
    const char* sep = "";

    auto first = std::begin(haystack);
    auto last = std::end(haystack);

    auto first_needle = std::begin(needle);
    auto last_needle = std::end(needle);
    auto needle_length = std::distance(first_needle, last_needle);

    while (first != last)
    {
        auto next = std::search(first, last, first_needle, last_needle);

        if (next == first)
        {
            first = std::next(first, needle_length);
        }
        else
        {
            std::cout << sep;
            std::copy(first, next, output_iter);
            sep = " ";
            first = next;
        }
    }
}

int main()
{
    using namespace std::literals;

    const auto needle = "FOO"s;

    const auto haystack = "FOOTHEFOOFOOBEST"s;

    separate(haystack, needle, std::ostream_iterator<char>(std::cout, ""));

    return 0;
}

预期输出:

THE BEST

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2013-12-18
    相关资源
    最近更新 更多