Answer to Question #157899 in C++ for Laiba

Question #157899

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



1
Expert's answer
2021-01-23T15:46:33-0500
#include <iostream>
#include <string>
#include <cctype>


using namespace std;


int main()
{
	string msg;
	cout << "Enter a string with 40 characters: ";
	getline(cin, msg);
	string msgFormat;
	for(int i = 0; i < msg.length(); i++)
	{
		if(isalpha(msg[i])) msgFormat += toupper(msg[i]);
	}
	int Counter = 0;
	char c[27];
	for(int i = 0; i < 27; i++) c[i] = '0';
	for(int i = 0; i < msgFormat.length(); i++)
	{
		for(int j = 0; j < 27; j++)
		{
			if(c[j] == msgFormat[i]) break;
			if(c[j] == '0') 
			{
				c[j] = msgFormat[i];
				Counter++;
				break;
			}
		}
	}
	cout << "Unique characters are: ";
	for(int i = 0; i < 27; i++)
	{
		if(c[i] != '0' && c[i+1] != '0') cout << c[i] << ", ";
		if(c[i] != '0' && c[i+1] == '0') cout << c[i] << endl;
		if(c[i] == '0') break;
	}
	for(int i = 0; i < Counter; i++)
	{
		for(int j = 0; j < Counter; j++)
		{
			if((int)c[j] > (int)c[j+1] && c[j+1] != '0')
			{
				char temp = c[j];
				c[j] = c[j+1];
				c[j+1] = temp;
			}
		}
	}
	
	cout << "Sorted: ";
	for(int i = 0; i < 27; i++)
	{
		if(c[i] != '0' && c[i+1] != '0') cout << c[i] << ", ";
		if(c[i] != '0' && c[i+1] == '0') cout << c[i] << endl;
		if(c[i] == '0') break;
	}
	cout << endl << "Enter any character and press 'Enter': ";
	cin >> c[0];


	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

Hamza
24.01.21, 06:51

This is very good website

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS