#include <algorithm> // for std::sort
#include <iostream> // for std::cout
#include <string> // for std::string
#include <vector> // for std::vector
// Extract all integer values from a string.
// This function walks through the characters, collects digits into a temporary buffer,
// and converts each completed number into an integer.
std::vector<int> extract_numbers(const std::string& input) {
std::vector<int> numbers;
std::string buffer;
for (char ch : input) {
if (std::isdigit(static_cast<unsigned char>(ch))) {
// Accumulate digits into a temporary buffer.
buffer.push_back(ch);
} else {
// When encountering a non-digit, flush the buffer if it contains a number.
if (!buffer.empty()) {
numbers.push_back(std::stoi(buffer));
buffer.clear();
}
}
}
// Flush any remaining number at the end of the string.
if (!buffer.empty()) {
numbers.push_back(std::stoi(buffer));
}
return numbers;
}
// Sort the extracted numbers using the language's built-in sorting algorithm.
// std::sort is highly optimized and widely used.
void sort_numbers(std::vector<int>& numbers) {
std::sort(numbers.begin(), numbers.end());
}
// Rebuild a string representation of the sorted numbers.
// This keeps the output simple and predictable.
std::string join_numbers(const std::vector<int>& numbers) {
std::string result;
for (size_t i = 0; i < numbers.size(); ++i) {
result += std::to_string(numbers[i]);
if (i + 1 < numbers.size()) {
result += " "; // Add spacing between numbers.
}
}
return result;
}
int main() {
// Example input containing numbers mixed with other characters.
std::string input = "1000withz7 and3 or 99 give42";
// Extract all numbers from the string.
auto numbers = extract_numbers(input);
// Sort the numbers.
sort_numbers(numbers);
// Convert sorted numbers back into a single string.
std::string output = join_numbers(numbers);
// Display the result.
std::cout << "Sorted numbers: " << output << '\n';
}
/*
run:
Sorted numbers: 3 7 42 99 1000
*/