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).
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=”java” manual=”%23%20Python%20program%20to%20print%20permutations%20of%20a%20given%20string%20with%0A%23%20spaces.%0A%20%0A%23%20Utility%20function%0Adef%20toString(List)%3A%0A%20%20%20%20s%20%3D%20%22%22%0A%20%20%20%20for%20x%20in%20List%3A%0A%20%20%20%20%20%20%20%20if%20x%20%3D%3D%20’%5C0’%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20break%0A%20%20%20%20%20%20%20%20s%20%2B%3D%20x%0A%20%20%20%20return%20s%0A%20%0A%23%20Function%20recursively%20prints%20the%20strings%20having%20space%20pattern.%0A%23%20i%20and%20j%20are%20indices%20in%20’str%5B%5D’%20and%20’buff%5B%5D’%20respectively%0Adef%20printPatternUtil(string%2C%20buff%2C%20i%2C%20j%2C%20n)%3A%0A%20%20%20%20if%20i%20%3D%3D%20n%3A%0A%20%20%20%20%20%20%20%20buff%5Bj%5D%20%3D%20’%5C0’%0A%20%20%20%20%20%20%20%20print%20toString(buff)%0A%20%20%20%20%20%20%20%20return%0A%20%0A%20%20%20%20%23%20Either%20put%20the%20character%0A%20%20%20%20buff%5Bj%5D%20%3D%20string%5Bi%5D%0A%20%20%20%20printPatternUtil(string%2C%20buff%2C%20i%2B1%2C%20j%2B1%2C%20n)%0A%20%0A%20%20%20%20%23%20Or%20put%20a%20space%20followed%20by%20next%20character%0A%20%20%20%20buff%5Bj%5D%20%3D%20’%20’%0A%20%20%20%20buff%5Bj%2B1%5D%20%3D%20string%5Bi%5D%0A%20%0A%20%20%20%20printPatternUtil(string%2C%20buff%2C%20i%2B1%2C%20j%2B2%2C%20n)%0A%20%0A%23%20This%20function%20creates%20buf%5B%5D%20to%20store%20individual%20output%20string%0A%23%20and%20uses%20printPatternUtil()%20to%20print%20all%20permutations.%0Adef%20printPattern(string)%3A%0A%20%20%20%20n%20%3D%20len(string)%0A%20%0A%20%20%20%20%23%20Buffer%20to%20hold%20the%20string%20containing%20spaces%0A%20%20%20%20buff%20%3D%20%5B0%5D%20*%20(2*n)%20%23%202n-1%20characters%20and%201%20string%20terminator%0A%20%0A%20%20%20%20%23%20Copy%20the%20first%20character%20as%20it%20is%2C%20since%20it%20will%20be%20always%0A%20%20%20%20%23%20at%20first%20position%0A%20%20%20%20buff%5B0%5D%20%3D%20string%5B0%5D%0A%20%0A%20%20%20%20printPatternUtil(string%2C%20buff%2C%201%2C%201%2C%20n)%0A%20%0A%23%20Driver%20program%0Astring%20%3D%20%22ABCD%22%0AprintPattern(string)%0A%20″ message=”JAVA” highlight=”” provider=”manual”/] [ad type=”banner”]