【问题标题】:Why did the output repeate again in some substring?为什么输出在某些子字符串中再次重复?
【发布时间】:2022-01-09 12:17:55
【问题描述】:
    #include <iostream>
    #include <string>
    #include <algorithm>
    int main()
    {
        std::string s = "abcdefg";
        int n = s.size();
        for (int i = 0; i < n;  i++)
        {
            for (int j = n; j > i; j--)
            {
                std::cout << s.substr(i,j) << std::endl;
            }
        }
    }

我想从abcdefg, abcdef,... a, 输出子字符串,然后bcdefg, bcdef...b,

但是,结果显示它在某些部分重复,例如cdefg在我的结果中重复了3次,为什么以及如何纠正它?

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    发生这种情况的原因是因为j 始终被设置为n。你告诉substr 给你n 计数超过i 这不是你想要的。您希望从i 到字符串的末尾,然后从那里减少。

    for (int j = n; j &gt; i; j--)更改

    for (int j = (n - i); j &gt; 0; j--)

    【讨论】:

      【解决方案2】:

      substr的第二个参数应该是count,即子串的长度,所以改

      std::cout << s.substr(i,j) << std::endl;
      

      std::cout << s.substr(i,(j-i)) << std::endl;
      

      LIVE

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 2017-05-10
        • 2021-01-27
        • 2020-01-10
        • 2017-06-16
        相关资源
        最近更新 更多