The simplest solution is to split the string into a collection of string then sort that collection and concatenate the result into a string again: you can use a custom comparator using the size of the string and feed it to std::stable_sort
with the collection of strings to sort:
// Your original string
std::string your_string = "sj a sa df r e w f d s a v c x z sd fd";
// Split the string
std::istringstream iss(your_string);
std::vector<std::string> words{
std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>()
};
// Stable sort by size
std::stable_sort(std::begin(words), std::end(words), [](const std::string& lhs, const std::string& rhs) {
return lhs.size() > rhs.size();
});
// Merge the results back with spaces
std::ostringstream oss;
std::copy(
std::begin(words), std::end(words),
std::ostream_iterator<std::string>(oss, " ")
);
your_string = oss.str();
Of course, this algorithm is not optimal. To avoid much of the computation, you could store directly a vector of strings and work with that instead of storing your words in a space-separated string. Among the suboptimals things: we copy many things from the original string while some things could probably be moved to and from the words
vector (not sure). The mere fact that we strip the spaces to add them back is a clear hint that we’re doing more than we could.
Also, note that the final string will have an additional trailing space that you can choose to remove with pop_back
.
2
solved About Sorting String In C++