You can use std::sort and a lambda where characters are compared using its lower case (std::tolower)
#include <algorithm>
#include <iostream>
int main()
{
std::string str;
std::cout << "Enter a sentence : ";
getline(std::cin, str);
std::sort(str.begin(), str.end(), [](const char& a, const char& b) {
if (std::tolower(a) == std::tolower(b))
return a > b;
else
return std::tolower(a) < std::tolower(b);
});
std::cout << str << std::endl;
return 0;
}
This will show
Enter a sentence : Hello Rohit
ehHillooRt
in the terminal. Note that the space is sorted in front of all the leters. If you want to delete the space you can do it with the the following line of code:
str.erase(std::remove_if(str.begin(), str.end(), [](unsigned char x) { return std::isspace(x); }), str.end());
If you also want to check for unwanted elements, you can use:
std::vector<std::string> unwanted_elements{ "!" }; // Coma separed list of strings that you don't want in the input. Note that this are full strings so you could also reject "Hello" for instance.
for (size_t i = 0; i < unwanted_elements.size(); ++i)
{
size_t idx = str.find(unwanted_elements[i]);
if (idx != std::string::npos)
{
std::cout << "Unwnated element " << unwanted_elements[i] << " at position " << idx << std::endl;
}
}
Then the whole program would be:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::string str;
std::cout << "Enter a sentence : ";
getline(std::cin, str);
std::vector<std::string> unwanted_elements{ "!" }; // Coma separed list of strings that you don't want in the input. Note that this are full strings so you could also reject "Hello" for instance.
for (size_t i = 0; i < unwanted_elements.size(); ++i)
{
size_t idx = str.find(unwanted_elements[i]);
if (idx != std::string::npos)
{
std::cout << "Unwnated element " << unwanted_elements[i] << " at position " << idx << std::endl;
return -1;
}
}
str.erase(std::remove_if(str.begin(), str.end(), [](unsigned char x) { return std::isspace(x); }), str.end());
std::sort(str.begin(), str.end(), [](const char& a, const char& b) {
if (std::tolower(a) == std::tolower(b))
return a > b;
else
return std::tolower(a) < std::tolower(b);
});
std::cout << str << std::endl;
return 0;
}
This solution works only for plain ascii characters.