![]() |
VOOZH | about |
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:
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:
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.