Divide a string in N equal parts

Program to print N equal parts of a given string.

Algorithm:
1) Get the size of the string using string function strlen() (present in string.h)
2) Get size of a part.

part_size = string_length/n
3) Loop through the input string. In loop, if index becomes multiple of part_size then put a part separator(“\n”)

Implementation:

/* Function to print n equal parts of str*/
void divideString(char *str, int n)
{
   int str_size = strlen(str);
   int i;
   int part_size;

   /*Check if string can be divided in n equal parts */
   if(str_size%n != 0)
   {
     printf("Invalid Input: String size is not divisible by n");
     return;
   }

   /* Calculate the size of parts to find the division points*/
   part_size = str_size/n;
   for(i = 0; i< str_size; i++)
   {
     if(i%part_size == 0)
        printf("\n"); /* newline separator for different parts */
     printf("%c", str[i]);
   }
}

int main()
{
    /*length od string is 28*/
    char *str = "a_simple_divide_string_quest";

    /*Print 4 equal parts of the string */
    divideString(str, 4);

    getchar();
    return 0;
}

In above solution, we are simply printing the N equal parts of the string. If we want individual parts to be stored then we need to allocate part_size + 1 memory for all N parts (1 extra for string termination character ‘\0′), and store the addresses of the parts in an array of character pointers.

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |

*