
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Possible Strings 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
#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
Advertisements