# Print all possible strings that can be made by placing spaces in C++

In this problem, we are given a string and we have to print all those string that can be made using this string by placing space in between the characters of the string.

Let’s take an example to understand the topic better −

Input: string = ‘XYZ’
Output: XYZ, XY Z, X YZ, X Y Z

To solve this problem, we will have to find all the possible ways in which we can put space in the string. For this we will use recursion. In this, we will place spaces on by one and generate a new string.

## Example

Live Demo

#include <iostream>
#include <cstring>
using namespace std;
void printPattern(char str[], char buff[], int i, int j, int n){
if (i==n){
buff[j] = '\0';
cout << buff << endl;
return;
}
buff[j] = str[i];
printPattern(str, buff, i+1, j+1, n);
buff[j] = ' ';
buff[j+1] = str[i];
printPattern(str, buff, i+1, j+2, n);
}
int main() {
char *str = "XYZ";
int n = strlen(str);
char buf[2*n];
buf[0] = str[0];
cout<<"The string generated using space are :\n";
printPattern(str, buf, 1, 1, n);
return 0;
}

## Output

The string generated using space are −

XYZ
XY Z
X YZ
X Y Z

Updated on: 17-Jan-2020

288 Views