Initialize a string of size 40. Write a program that prints all unique alphabets from c-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
Here is the code! Because c-strings are required, I mostly used c functions instead of c++ ones.
#include <cstdio>
#include <string>
//number of letters
const int SIZE = 'Z' - 'A' + 1;
int main()
{
//get string
char string[40];
printf("Enter the string: ");
fflush(stdout);
scanf("%[^\n]", string);
//letters, found in text
bool meet[SIZE], first = true;
for (int i = 0; i < SIZE; i++) meet[i] = false;
printf("Unique characters are: ");
//go through all letters
for (int i = 0; i < 40 && string[i]; i++)
{
char c = toupper(string[i]);
if (c >= 'A' && c <= 'Z' && !meet[c - 'A'])
{
if (first)
{
printf("%c", c);
first = false;
}
else
printf(", %c", c);
meet[c - 'A'] = true;
}
}
//sorted
first = true;
printf("\nSorted: ");
for (int i = 0; i < SIZE; i++)
{
if (meet[i])
{
if (first)
{
printf("%c", i + 'A');
first = false;
}
else
printf(", %c", i + 'A');
}
}
printf("\n");
fflush(stdout);
return 0;
}
Comments
Leave a comment