#include <stdio.h> // for printf
#include <stdlib.h> // for malloc, realloc, qsort, strtol
#include <ctype.h> // for isdigit
#include <string.h> // for strlen
/*
Extract all integer values from a mixed string.
This function walks through the characters, collects digits into a temporary buffer,
and converts each completed number into an integer.
*/
int* extract_numbers(const char* input, size_t* out_count) {
size_t capacity = 8; // initial capacity for dynamic array
size_t count = 0; // how many numbers we have collected
int* numbers = malloc(capacity * sizeof(int));
char buffer[64] = ""; // temporary buffer for digits
size_t buf_len = 0;
for (size_t i = 0; input[i] != '\0'; ++i) {
if (isdigit((unsigned char)input[i])) {
/* accumulate digits */
if (buf_len < sizeof(buffer) - 1) {
buffer[buf_len++] = input[i];
}
} else {
/* flush buffer if it contains a number */
if (buf_len > 0) {
buffer[buf_len] = '\0';
int value = (int)strtol(buffer, NULL, 10);
if (count == capacity) {
/* grow the dynamic array */
capacity *= 2;
numbers = realloc(numbers, capacity * sizeof(int));
}
numbers[count++] = value;
buf_len = 0;
}
}
}
/* flush any remaining number at the end */
if (buf_len > 0) {
buffer[buf_len] = '\0';
int value = (int)strtol(buffer, NULL, 10);
if (count == capacity) {
capacity *= 2;
numbers = realloc(numbers, capacity * sizeof(int));
}
numbers[count++] = value;
}
*out_count = count;
return numbers;
}
/*
Comparison function for qsort.
qsort is efficient and widely used for sorting in C.
*/
int compare_ints(const void* a, const void* b) {
int ia = *(const int*)a;
int ib = *(const int*)b;
return (ia > ib) - (ia < ib);
}
/*
Print all numbers in a simple space-separated format.
*/
void print_numbers(const int* numbers, size_t count) {
for (size_t i = 0; i < count; ++i) {
printf("%d", numbers[i]);
if (i + 1 < count) {
printf(" ");
}
}
printf("\n");
}
int main(void) {
const char* input = "1000withz7 and3 or 99 give42";
/* extract numbers */
size_t count = 0;
int* numbers = extract_numbers(input, &count);
/* sort numbers */
qsort(numbers, count, sizeof(int), compare_ints);
/* display result */
printf("Sorted numbers: ");
print_numbers(numbers, count);
free(numbers);
return 0;
}
/*
run:
Sorted numbers: 3 7 42 99 1000
*/