Reputation: 410
I have a string where I need to do substring operation. I'm trying to achieve something like this for example if the input string is com
then the output must be something like this -
c
co
com
o
om
m
.. I have tried this
for(int i=0 ; i<len ;i++)
{
printf("%s",&string[strlen(string)-i]));
}
Upvotes: 0
Views: 4967
Reputation: 1
Below is the code to find all substrings of a string in javascript without for loop, which will increase the speed of code.
const devideSubStr = (str) => {
var totalLoop = str.length * ((str.length + 1)/2);
// looping count
let i = 0;
var totalChar = 1;//character to get
var charFrom = 0;// from which index
var strLength = str.length;//length of digit
while( i < totalLoop){
console.log(str.substr(charFrom, totalChar))
charFrom ++;
i ++;
if(charFrom == strLength){
charFrom = 0;
strLength = strLength - 1;
totalChar ++;
}
}}
Upvotes: -1
Reputation:
We have to iterate through the first element of string and print all the substring and than onwards one by one we increment the index of i and printing the substring from range (j to k)
public void generateSubString(String source){
char[] arr = source.toCharArray();
for(int i = 0; i<arr.length; i++){
for(int j = i ; j < arr.length; j++){
for(int k = i; k<=j; k++){
System.out.print(arr[k]);
}
System.out.println();
}
OUTPUT:
S ST STA STAC STACK T TA TAC TACK A AC ACK C CK K
Upvotes: 0
Reputation: 36458
You're missing a comma in your code:
for(int i=0 ; i<len ;i++)
{
printf("%s", &string[strlen(string)-i])
}
But that will print "", "m", "om" - not what you want.
Something more like:
// start at each point in the string
for ( const char *start = string; *start; ++start )
{
// for each starting point, go from the whole remainder down
// to just one character
for ( const char *end = string + strlen(string); end > start; --end )
{
for ( const char *s = start; s < end; ++s )
putchar(*s);
putchar('\n');
}
}
Example: https://ideone.com/XXoYv6
Upvotes: 0
Reputation: 3189
A substring is defined by its left and right ends so there are O(n*n)
substrings in a string of length n
.
int n = strlen(string);
for(int i = 0; i < n; i++)
{ for(int j = i; j < n; j++)
{ /* print substring from i to j */
for(int k = i; k <= j; k++)
{ printf("%c", string[k]);
}
printf("\n");
}
}
Upvotes: 4