Description: Write a program to divide(and print) a string into N equal parts.

 
If video does not load, Click here
 
Example:

Input string: “ipupilisgold”

for N=4:

Output:

ipu

pil

isg

old

Algorithm:

1) Compute the length of the string.

You can do one of the following:

-Traverse the string till ‘\0’ (end characters) is encountered.

-Alternatively, use a pre-defined function like ‘strlen’ in C.

2) Compute the size of a part.

size=length of string/ N;

3) Iterate through the length of the string.

-If the value of the index is an integral multiple of the size, put a line separator (\n) and then output the character.

-Else, output the character.

Implementation using C:
 

#include<stdio.h>

#include<string.h>/*used for function'strlen'*/

 

/*Function to print output*/

void divide(char *string, int n)

{

   int length = strlen(string);

   int j;

   int size;

 

   /*Check if string can be divided in n equal parts */

   if(length%n != 0)

   {

            printf("String cannot be divided in equal parts");

            return;

   }

 

   /* Calculate the size of each part*/

   size = length/n;

   for(j=0;j<length;j++)

   {

            if(j%size == 0)

            printf("\n"); /* newline separator for different parts */

            printf("%c", string[j]);

   }

}

int main()

{  

            char *string = "ipupilisgold";

            int N=4;

            /*Divide the string in 4 equal parts of the string */

            divide(string, N);

            printf("\n");

            return 0;

}

Go to top