Answer to Question #158121 in C++ for Moez inam

Question #158121

Initialize a string of size 40. Write a program that prints all unique alphabets from string. After printing

them sort them in ascending order.

For example: Hi world I am here to help you.

Unique characters are: H, I, W, O, R, L, D, A, M, E, T, P, Y, U.

Sorted: A, D, E, H, I, L, M, O, P, R, T, U, W, Y 

in c++


1
Expert's answer
2021-01-25T00:54:03-0500
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
  string s = "Hi world I am here to help you.";      //declare the input string
  int alphabets[26] = {0};                          //declare array of size 26, to mark seen alphabets

  int index;

  cout << "Unique Alphabets\n";
  for(int i = 0; i < s.length(); i++)                  //loop through each char of string
  {
      if(isalpha(s[i]))                              //if char is alphabet
      {
          index = tolower(s[i]) - 'a';              //convert it into lowercase and get index 0-25
          if(!alphabets[index]){                      //if that alphabet is not seen previously
              cout << (char)toupper(s[i]) << ", ";  //print its uppercase
              alphabets[index] = 1;                  //mark the alphabet as seen
          }
      }
  }

  char ch;
  cout << "\n\nSorted Alphabets\n";
  for(int i = 0; i < 26; i++)                          //loop through the seen alphabet indices
  {
      if(alphabets[i])                              //if alphabet was seen in string
      {
          ch = i + 'a';                              //convert it into character
          cout << (char)toupper(ch) << ", ";          //print the alphabet
      }
  }
  cout << endl;
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog