簡體   English   中英

如何一次從字符串中刪除一個字符?

[英]How do I delete one character from a string at a time?

我試圖弄清楚如何從字符串中一次刪除一個字符,這樣我就可以獲得所有版本的字符串,一次只丟失一個字符。 這就是我想要做的工作,但無濟於事。

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

它顯然適用於第一個,但隨后刪除其余的。 JON應該具有ON JN JO的預期輸出

您沒有在每次循環迭代時將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;
}

最簡單的方法是每次都復制一個字符串,然后修改副本:

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)++不屬於那里。

試試這個簡單直接:

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

使用迭代器和臨時副本的解決方案:

#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

這一切都非常低效。

只需復制一個沒有最后一個字符的副本,然后慢慢地迭代迭代,用原始字符替換該副本的結尾。

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));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM