Print all distinct characters of a string in order in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string. Our task is to print all distinct characters of the string in the order they appear in the string.

Let’s take an example to understand our problem,

Input: tutorials Point
Output: uralsPn

There are multiple ways to solve this problem but we will discuss the most effective one. The simple one includes the nesting of loops.

For this, we will use two arrays of size 256(8-bit characters are stored).

First we will initialize all values of counter array to 0 and all values of index array to n (length of string). On traversal of the string str and for every character c, increase count[x], if count[x] = 1, index[x] = i. If count[x] = 2, index[x] = n. Sort indexes and print characters.

Example

The code to show the implementation of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
void printDistinctCharacters(string str) {
   int n = str.length();
   int count[MAX_CHAR];
   int index[MAX_CHAR];
   for (int i = 0; i < MAX_CHAR; i++) {
      count[i] = 0;
      index[i] = n;
   }
   for (int i = 0; i < n; i++) {
      char x=str[i];
      ++count[x];
      if (count[x] == 1 && x !=' ')
         index[x] = i;
      if (count[x] == 2)
         index[x] = n;
   }
   sort(index, index+MAX_CHAR);
   for (int i=0; i<MAX_CHAR && index[i] != n; i++)
   cout<<str[index[i]]<<" ";
}
int main() {
   string str = "tutorialsPoint";
   cout<<"All distinct Characters of the string '"<<str<<"' are :\n";
   printDistinctCharacters(str);
   return 0;
}

Output

All distinct Characters of the string 'tutorialsPoint' are −
u r a l s P n
raja
Published on 22-Jan-2020 12:26:53
Advertisements