Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

How to extract and sort numbers from a string containing numbers and text in Rust

1 Answer

0 votes
/// Program to extract and sort unsigned integers embedded within text.
///
/// Demonstrates clean functional transformations, iterator chaining,
/// and fast zero-allocation string parsing primitives in Rust.

/// Parses an input string slice, locates all contiguous digit sequences,
/// and converts them into a list of 64-bit unsigned integers.
///
/// # Arguments
/// * `input` - A string slice containing text and embedded numbers.
///
/// # Returns
/// A `Vec<u64>` containing all extracted numbers in order of appearance.
fn extract_numbers(input: &str) -> Vec<u64> {
    // `split` partitions the string slice wherever the predicate returns true.
    // By splitting on non-digit characters (`!c.is_ascii_digit`), we get an iterator
    // over contiguous sequences of digits and empty string slices.
    input
        .split(|c: char| !c.is_ascii_digit())
        // Filter out empty slices resulting from consecutive non-digit characters
        .filter(|s| !s.is_empty())
        // Parse each slice into a 64-bit integer; `filter_map` ignores values that overflow or fail to parse
        .filter_map(|s| s.parse::<u64>().ok())
        // Collect iterator items into a dynamically allocated vector
        .collect()
}

/// Sorts a vector of integers in ascending order in-place using pattern-matching / Timsort.
///
/// Rust's `sort()` method is stable and operates with O(N log N) time complexity.
fn sort_numbers(numbers: &mut [u64]) {
    numbers.sort();
}

fn main() {
    let input_str = "1000withz7 and3 or 99 give42";

    println!("Input String:      \"{}\"", input_str);

    // Extract numbers using functional iterator pipeline
    let mut extracted_nums = extract_numbers(input_str);
    println!("Extracted Numbers: {:?}", extracted_nums);

    // Sort the extracted numbers in-place
    sort_numbers(&mut extracted_nums);
    println!("Sorted Numbers:    {:?}", extracted_nums);
}



/*
run:

Input String:      "1000withz7 and3 or 99 give42"
Extracted Numbers: [1000, 7, 3, 99, 42]
Sorted Numbers:    [3, 7, 42, 99, 1000]

*/

 



answered Aug 13 by avibootz
...