![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 consecutive characters together in a line in C++
In this problem, we are given a string of characters and we have to print the same string in such a way that if two or more characters are consecutive then print them together in a single line otherwise print them in different lines i.e. with a line break.
Let’s take an example to understand the concept better,
Input : abcxstk Output : abc x st k
Explanation − Since abc are in a sequence they are printed in a line. Then comes x which is not in sequence, so we add a linebreak here. Next is s which is not a sequence with x so we add a linebreak. Next is t which is in sequence with s so printed in sequence. Next is k which is not in sequence with t so we add a linebreak.
Here, we will check an element with its previous element in the string. If they are in sequence then print normally. Otherwise, print the element with a line break.
Example
Now, let’s create a program based on this logic
#include <iostream> using namespace std; int main(){ string str = "stukfrpq"; cout << str[0]; for (int i=1; str[i]!='\0'; i++){ if ((str[i] == str[i-1]+1) || (str[i] == str[i-1]-1)) cout << str[i]; else cout << "\n" << str[i];; } return 0; }
Output
stu k f r pq