Common characters in n strings | CPP Program to find all the common characters in n strings ; primary array for common characters we assume all characters are seen before . ; for each string ; secondary array for common characters Initially marked false ; for every character of ith string ; if character is present in all strings before , mark it . ; copy whole secondary array into primary ; displaying common characters ; Driver 's Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void commonCharacters ( string str [ ] , int n ) { bool prim [ MAX_CHAR ] ; memset ( prim , true , sizeof ( prim ) ) ; for ( int i = 0 ; i < n ; i ++ ) { bool sec [ MAX_CHAR ] = { false } ; for ( int j = 0 ; str [ i ] [ j ] ; j ++ ) { if ( prim [ str [ i ] [ j ] - ' a ' ] ) sec [ str [ i ] [ j ] - ' a ' ] = true ; } memcpy ( prim , sec , MAX_CHAR ) ; } for ( int i = 0 ; i < 26 ; i ++ ) if ( prim [ i ] ) printf ( " % c ▁ " , i + ' a ' ) ; } int main ( ) { string str [ ] = { " geeksforgeeks " , " gemkstones " , " acknowledges " , " aguelikes " } ; int n = sizeof ( str ) / sizeof ( str [ 0 ] ) ; commonCharacters ( str , n ) ; return 0 ; }