# Print consecutive characters together in a line in C++

C++Server Side ProgrammingProgramming

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

Live Demo

#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
Published on 03-Jan-2020 07:44:11