【问题标题】:How i can get all substring of size k of string?我怎样才能得到所有大小为k的字符串子字符串?
【发布时间】:2021-12-14 17:27:27
【问题描述】:

我不知道我的代码中的错误在哪里?有人可以帮我解决它。

我的代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
void solution() {
   string s;
   ll k;
   cin >> s >> k;
   for(int i=0; i<=s.length()-k; i++) {
       for(int r=k-1; r<s.length(); r++){
           cout << s.substr(i,r) << endl;
       }
   }
}
int main() {
    ll t;
    cin >> t;
    while(t--){
         solution();
    }
    return 0;
}

输入:

1
ABCD 3

预期输出:

ABC
BCD

实际输出:

AB
ABC
BC
BCD

【问题讨论】:

  • 听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programsDebugging Guide
  • 我投票认为#include&lt;bits/stdc++.h 是您的代码中出现错误的地方。包含文件不是标准的 C++;而是特定的特殊编译器。
  • 顺便说一句,如果你需要定义缩写宏,你应该投资一些键盘类。在专业编程中,这种编码风格不受欢迎,可能会被解雇。
  • 如果这是竞赛编程,你应该将s.lengths.length - k分配给常量临时变量。除非您有智能编译器并相应地设置优化级别,否则每次迭代都会评估(执行)表达式。
  • 你的代码应该做什么?相反,它做了什么?请显示minimal reproducible example,其中包含输入、预期输出和实际输出

标签: c++ string


【解决方案1】:

我不知道你为什么需要一个嵌套的 for 循环。为什么不简单:

void solution() {
   string s;
   ll k;
   cin >> s >> k;

   for(int i = 0; i <= s.length() - k; i++) {
     cout << s.substr(i, k) << endl;
   }
}

【讨论】:

    【解决方案2】:

    这是一种获取所有给定长度的子字符串的方法:

    #include<string>
    #include<iostream>
    
    int main() {
        int input = 0;
        std::string str = "";
        std::cin >> input >> str;    //This is the length of substring you wanna get
        for (int i = str.size() - input; i >= 0; i--){
            std::cout << str.substr(i, input) << " ";    //output the result from end to begin
        }
    }
    

    不检查空输入。正确的输入会输出一个降序的答案。

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 2020-04-08
      • 2016-10-16
      • 2019-12-29
      • 2014-05-27
      • 2021-01-23
      相关资源
      最近更新 更多