Counts of distinct consecutive sub-string of length two using C++ STL



In this tutorial, we will be discussing a program to count distinct consecutive sub-string of length two using C++ STL.

For this we will provided with a string. Our task is to count and print all the unique substrings of length two from the given string.

Example

 Live Demo

#include<bits/stdc++.h> using namespace std; void calc_distinct(string str){    map<pair<char,char>, int> dPairs;    for (int i=0; i<str.size()-1; i++)       dPairs[make_pair(str[i], str[i+1])]++;    cout << "Distinct sub-strings with counts:\n";    for (auto it=dPairs.begin(); it!=dPairs.end(); it++)       cout << it->first.first << it->first.second << "-" << it->second << " "; } int main(){    string str = "abcacdcacabacaassddssklac";    calc_distinct(str);    return 0; }

Output

Distinct sub-strings with counts: aa-1 ab-2 ac-4 as-1 ba-1 bc-1 ca-4 cd-1 dc-1 dd-1 ds-1 kl-1 la-1 sd-1 sk-1 ss-2
Updated on: 2020-03-16T10:04:44+05:30

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements