Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.

Input:  str[] = "ABC"
Output: ABC
        AB C
        A BC
        A B C

The idea is to use recursion and create a buffer that one by one contains all output strings having spaces. We keep updating buffer in every recursive call. If the length of given string is ā€˜nā€™ our updated string can have maximum length of n + (n-1) i.e. 2n-1. So we create buffer size of 2n (one extra character for string termination).

[ad type=”banner”] We leave 1st character as it is, starting from the 2nd character, we can either fill a space or a character. Thus one can write a recursive function like below.

[pastacode lang=”c” manual=”%2F%2F%20C%2B%2B%20program%20to%20print%20permutations%20of%20a%20given%20string%20with%20spaces.%0A%23include%20%3Ciostream%3E%0A%23include%20%3Ccstring%3E%0Ausing%20namespace%20std%3B%0A%20%0A%2F*%20Function%20recursively%20prints%20the%20strings%20having%20space%20pattern.%0A%20%20%20i%20and%20j%20are%20indices%20in%20’str%5B%5D’%20and%20’buff%5B%5D’%20respectively%20*%2F%0Avoid%20printPatternUtil(char%20str%5B%5D%2C%20char%20buff%5B%5D%2C%20int%20i%2C%20int%20j%2C%20int%20n)%0A%7B%0A%20%20%20%20if%20(i%3D%3Dn)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20buff%5Bj%5D%20%3D%20’%5C0’%3B%0A%20%20%20%20%20%20%20%20cout%20%3C%3C%20buff%20%3C%3C%20endl%3B%0A%20%20%20%20%20%20%20%20return%3B%0A%20%20%20%20%7D%0A%20%0A%20%20%20%20%2F%2F%20Either%20put%20the%20character%0A%20%20%20%20buff%5Bj%5D%20%3D%20str%5Bi%5D%3B%0A%20%20%20%20printPatternUtil(str%2C%20buff%2C%20i%2B1%2C%20j%2B1%2C%20n)%3B%0A%20%0A%20%20%20%20%2F%2F%20Or%20put%20a%20space%20followed%20by%20next%20character%0A%20%20%20%20buff%5Bj%5D%20%3D%20’%20’%3B%0A%20%20%20%20buff%5Bj%2B1%5D%20%3D%20str%5Bi%5D%3B%0A%20%0A%20%20%20%20printPatternUtil(str%2C%20buff%2C%20i%2B1%2C%20j%2B2%2C%20n)%3B%0A%7D%0A%20%0A%2F%2F%20This%20function%20creates%20buf%5B%5D%20to%20store%20individual%20output%20string%20and%20uses%0A%2F%2F%20printPatternUtil()%20to%20print%20all%20permutations.%0Avoid%20printPattern(char%20*str)%0A%7B%0A%20%20%20%20int%20n%20%3D%20strlen(str)%3B%0A%20%0A%20%20%20%20%2F%2F%20Buffer%20to%20hold%20the%20string%20containing%20spaces%0A%20%20%20%20char%20buf%5B2*n%5D%3B%20%2F%2F%202n-1%20characters%20and%201%20string%20terminator%0A%20%0A%20%20%20%20%2F%2F%20Copy%20the%20first%20character%20as%20it%20is%2C%20since%20it%20will%20be%20always%0A%20%20%20%20%2F%2F%20at%20first%20position%0A%20%20%20%20buf%5B0%5D%20%3D%20str%5B0%5D%3B%0A%20%0A%20%20%20%20printPatternUtil(str%2C%20buf%2C%201%2C%201%2C%20n)%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20functions%0Aint%20main()%0A%7B%0A%20%20%20%20char%20*str%20%3D%20%22ABCD%22%3B%0A%20%20%20%20printPattern(str)%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”c” highlight=”” provider=”manual”/] [ad type=”banner”]