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++
#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;
}
Comments
Leave a comment