问题描述
我想获取所有可能的子字符串,有以下代码(包括所有库),其中n是字符串s的长度:
long substrCount(int n,string s) {
string sub;
vector<string> s2;
for(int i = 0; i<n; ++i){
for(int j = 0; j <= n-i; j++){
sub = s.substr(i,j);
if(sub != "")
s2.push_back(sub);
}
}
但是当我尝试使用主字符串“ asasd”时,我得到了
> s2
> ={a,as,asa,asas,asasd,a,s,sa,sas,sasd,asd,sd,d}
我不明白为什么,索引i从0到n。我应该在第一次asasd之后以“ s”开头的字符串。
解决方法
由于您的问题没有提供足够的详细信息。我可以为您提供替代方案。对于本示例,我不使用vector
例如:
#include <iostream>
#include <string>
void subString(std::string,int);
int main()
{
std::string s2 = "asad";
subString(s2,s2.length());
return 0;
}
void subString(std::string s,int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 1; j <= n - i; j++)
std::cout << s.substr(i,j) << std::endl;
}
}
输出:
a
as
asa
asad
s
sa
sad
a
ad
d
,
因为首先将i固定为0,然后遍历整个基于j的循环,然后将i递增为1,然后重新执行基于j的循环,依此类推... 您可以使用调试器方便地进行检查。