You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改C++代码实现字符串后缀子串的递增式输出?

问题解决:调整C++代码输出顺序

你的代码当前是从字符串开头截断输出,要实现从末尾单字符逐步扩展到完整单词的效果,只需修改外层循环的遍历方向:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string word;
    cout << "Enter the word: ";
    cin >> word;
    // 外层循环从字符串最后一个索引开始,递减至0
    for (int i = word.length() - 1; i >= 0; --i) {
        // 输出从索引i到字符串末尾的所有字符
        for (int j = i; j < word.length(); ++j) {
            cout << word[j];
        }
        cout << endl;
    }
    return 0;
}

修改说明

原代码外层循环i从0开始递增,每次输出从i到末尾的子串,导致输出顺序为「完整单词→末尾单字符」。调整后,外层循环从字符串最后一个索引(word.length()-1)开始递减,每次输出的子串起始位置逐步前移,最终得到d→rd→ord→word的目标顺序。

内容的提问来源于stack exchange,提问作者Salih Sultan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 08:20:50