Reputation: 65
I want to get all the sub string possible, there is the following code for it (with all library included), which n is the length of the string 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);
}
}
But when I tried with the main for the string "asasd", I get
> s2
> ={a,as,asa,asas,asasd,a,as,asa,asas,asasd,s,sa,sas,sasd,a,as,asa,asas,asasd,s,sa,sas,sasd,a,as,asd,a,as,asa,asas,asasd,s,sa,sas,sasd,a,as,asd,s,sd,a,as,asa,asas,asasd,s,sa,sas,sasd,a,as,asd,s,sd,d}
I do not understand why, the index i is from 0 to n. I should have the string beginning by 's' just after the first asasd.
Upvotes: 2
Views: 67
Reputation: 1539
Since you did not provide enough detail in your question. I can provide you with an alternative. For this example I don't use a vector
For example:
#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;
}
}
Output:
a
as
asa
asad
s
sa
sad
a
ad
d
Upvotes: 1
Reputation: 360
Because first you fix i to 0 and you iterate over the entire j-based loop, then you increment i to 1and re-do the j based loop, and so on... You can check this easily with a debugger.
Upvotes: 0