VOOZH about

URL: https://www.geeksforgeeks.org/dsa/divide-a-string-in-n-equal-parts/

⇱ Divide a string in N equal parts - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Divide a string in N equal parts

Last Updated : 23 Jul, 2025

Difficulty Level: Rookie
Question: 
Write a program to print N equal parts of a given string. 

Solution: 
1) Get the size of the string using string function strlen() (present in the string.h) 
2) Get the 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: 


Output
a_simpl
e_divid
e_strin
g_quest

Time Complexity: O(n), where n is the length

 of string.

Auxiliary Space: O(1).

In the above solution, n equal parts of the string are only printed. If we want individual parts to be stored, 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. 

Another Approach: Using STL in C++
Implemention:


Output
a_simpl
e_divid
e_strin
g_quest

Time Complexity: O(n), where n is the length of string.

Auxiliary Space: O(n), because when string is passed to the function it creates a copy of itself (passing by value).

Plein case write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Comment
Article Tags:
Article Tags: