Print consecutive characters together in a line

Given a sequence of characters, print consecutive sequence of characters in a line, otherwise
print it in a new line.

Examples:

Input  : ABCXYZACCD
Output : ABC
         XYZ
         A
         C
         CD

Input : ABCZYXACCD
Output: ABC
        ZYX
        A
        C
        CD

The idea is to traverse string from left to right. For every traversed character, print it in a line if it is consecutive to previous one, else print a new line character.

// C++ program to print consecutive characters
// together in a line.
#include <iostream>
using namespace std;

void print(string str)
{
    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];;
    }
}

// Driver code
int main()
{
    string str = "BCBC";
    print(str);
    return 0;
}

Output:

ABC
XYZ
A
C
CD

This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice





Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.