如何一次从字符串中删除一个字符?

时间:2016-12-06 01:25:15

标签: c++ string loops

我试图弄清楚如何从字符串中一次删除一个字符,这样我就可以获得所有版本的字符串,一次只丢失一个字符。这就是我想要做的工作,但无济于事。

for(int i = 0 ; i < s.length() ; i++){
    tmp.erase(0, i);
    std::cout << tmp << std::endl;
    s.at(i)++;
}

它显然适用于第一个,但随后删除其余的。 JON应该具有ON JN JO的预期输出

5 个答案:

答案 0 :(得分:2)

您没有在每次循环迭代中将tmp重置为原始字符串值,因此它会一直从tmp中删除越来越多的字符,直到它为空。

您还在每次循环迭代中删除了错误的字符范围。

您还要在每次循环迭代中修改原始字符串,以增加其各个字符的值。你为什么这样做呢?

尝试更像这样的东西:

for(std::string::size_type i = 0 ; i < s.length() ; i++){
    std::string tmp = s;
    tmp.erase(i, 1);
    std::cout << tmp << std::endl;
}

答案 1 :(得分:1)

最简单的方法是每次都复制一个字符串,然后修改副本:

for(std::string::size_type i = 0 ; i < s.size() ; i++){
    auto tmp=copy;
    tmp.erase(i, 1);
    std::cout << tmp << std::endl;
}

为了正确,索引变量应为std::string::size_typelength()size()返回(size_tsize()自然归属于一起)。

你的代码几乎是正确的,除了它每次都忽略了复制字符串,s.at(i)++不属于那里。

答案 2 :(得分:0)

尝试这一个简单直接:

while (TMP.size()) {
    cout << TMP << '\n';
    TMP.erase(0, 1);
}

答案 3 :(得分:0)

使用迭代器和临时副本的解决方案:

#include <iostream>
#include <string>
int main()
{
    std::string s("abcdefg");
    for (auto i = s.begin(); i != s.end(); ++i)
    {
        const std::string b = { s.begin(), i }; // temp copy!
        const std::string e = { i + 1, s.end() }; // temp copy!
        std::cout << b << e << '\n';
    }
}

没有临时副本的解决方案,C ++ 20 std::string_view

#include <iostream>
#include <string>
#include <string_view>
int main()
{
    std::string s("abcdefg");
    for (auto i = s.begin(); i != s.end(); ++i)
    {
        const std::string_view b = { s.begin(), i };
        const std::string_view e = { i + 1, s.end() };
        std::cout << b << e << '\n';
    }
}

输出:

bcdefg
acdefg
abdefg
abcefg
abcdfg
abcdeg
abcdef

答案 4 :(得分:0)

那简直是效率低下。

只需制作一个没有最后一个字符的副本,然后慢慢地进行迭代,用原始字符替换副本的末尾即可。

template <class F>
void do_with_one_missing(std::string_view s, F f) {
    auto i = size(s);
    if (i-- > 0) return;
    std::string x = s.remove_suffix(1);
    f(std::as_const(x));
    while (i-- > 0) {
        x[i] = x[i + 1];
        f(std::as_const(x));
    }
}
相关问题