Wednesday 27 July 2011

Finding Sub-Strings.

Print all the substrings of a given string.?
Eg: For "abc" the possible substrings are {"a","b","c","ab","bc","abc"}


Algorithm:
1) Start with two nested loops (let the loop variables are i and j, initialize them to 0)
2) Store the sum of the loop variables in another variable(say k) and store the value of (k+1)th element of the string in temporary variable(say tmp).
3) Now set the (k+1)th element of string to 0.(so that it does not print the characters after that element)
4) print the string.(expression as :s+j - so that it starts printing after the j th element in the string).
5) Now store the value of temp into the (k+1)th element of the string.
6) Repeat the steps 2 to 5 till reaching the end of the string(i.e till the termination of first loop).


Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[]="abc";
int i,j;
clrscr();
for( i=0;i <strlen(s);i++)
{
for( j=0;j <strlen(s)-i;j++)
{
int k=j+i;
char tmp=s[k+1];
s[k+1]=0;
printf("%s\n",s+j);
s[k+1]=tmp;
}
}
getch();
}

No comments:

Post a Comment