Friday 30 March 2018

Printing all subsets of given string in C/C++

In C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<string>subst;
    string s;
 
    cin>>s;
    int l=s.length();
    for(int i=0;i<l;i++)
    {
        for(int j=1;j<=l-i;j++) // we take substring of length j from index i
            subst.push_back(s.substr(i,j));
    }
 
    sort(subst.begin(),subst.end());  // to sort substrings lexicographically
 
    for(auto t:subst)   //for displaying subsets
        cout<<t<<endl;
 
    return 0;

}
Input:
dab

Output:
a
ab
b
d
da
dab

In C
#include<stdio.h>
#include<string.h>
int main()
{
  char st[100],t[100];
  int i,l,j=0,k;
  scanf("%s",st);
  l=strlen(st);
  for(k=0;k<l;k++)
  {
        for(i=k;i<l;i++)
        {
    t[j++]=st[i];
    t[j]='\0';
    printf("%s\n",t);
        }
        j=0;
    }

    return 0;
}

Input:
abcd

Output:
a
ab
abc
abcd
b
bc
bcd
c
cd
d

1 comment: