Start learning free

LESSON 24 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in Rust: Sorting by a Field with split and nth

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

fn sort_lines(lines: Vec<String>, field: i32) -> String

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Rust's slice sort_by is a stable sort (use it, not sort_unstable_by). Write a helper that extracts the field by splitting on commas, compare those keys in the comparator, and join the result with the built-in join.

fn extract_field(line: &str, field: i32) -> String {
    line.split(',').nth((field - 1) as usize).unwrap_or("").to_string()
}


The full solution:
impl Solution {
    fn extract_field(line: &str, field: i32) -> String {
        line.split(',').nth((field - 1) as usize).unwrap_or("").to_string()
    }
    fn sort_lines(lines: Vec<String>, field: i32) -> String {
        let mut sorted_lines = lines.clone();
        sorted_lines.sort_by(|a, b| Solution::extract_field(a, field).cmp(&Solution::extract_field(b, field)));
        return sorted_lines.join("\n");
    }
}

STEP 1 OF 8
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in Rust, explained

    Problem overview

    Version 4 adds the -k flag. Each line is comma-separated and has at least field fields, and an empty field is allowed, as in "a,,c". sort_lines(lines, field) sorts the lines by the text of the 1-indexed field number field, compared by character code, and returns the original lines joined with \n. Lines whose fields are equal keep their original relative order. An empty list gives the empty string.

    With field = 2 and ["alice,30", "bob,25", "carol,40"], the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40". The whole line is returned, not only the key.

    Approach

    The earlier versions compared whole lines. Here the comparison is on a key taken out of each line, so the solution splits into two parts: a helper, extract_field, that returns the key of one line, and the sort that uses it. The sort is sort_by with a closure that compares the keys of two lines. sort_by is stable, so equal keys keep their input order, as the task requires.

    The keys are compared as strings, not as numbers. For ["x,10", "y,9"] with field 2 the result is "x,10\ny,9", because "10" is less than "9" as text.

    The helper builds a fresh String for each key, and the closure calls it twice per comparison, so every line's key is rebuilt many times during the sort. For a small tool that is fine and keeps the code easy to read. If the lines were very long or numerous, you could compute each key once with sort_by_cached_key, which stores the keys next to the elements while sorting. The lesson keeps the plain sort_by, which is what the steps follow.

    Step by step

    1. Split the line at commas with split(','). It doesn't build a vector; it gives an iterator that produces the pieces one at a time.
    2. Take the piece at position field - 1 with nth. Fields count from 1 and positions from 0, and nth wants a usize, so the number is converted with as usize. The result is an Option, empty if the piece doesn't exist.
    3. Fall back to an empty string with unwrap_or(""), so a missing field counts as an empty key.
    4. Make the key owned with to_string(). The piece borrows from the line, and the function returns a String. This expression has no semicolon, so it is the function's result.
    5. In sort_lines, make a mutable sorted_lines that is a clone of lines.
    6. Call sort_by with a closure over a and b.
    7. Compare the keys of a and b with cmp, passing a reference to the second key.
    8. Join the lines with "\n" and return.

    The solution in Rust

    impl Solution {
        fn extract_field(line: &str, field: i32) -> String {
            line.split(',')
                .nth((field - 1) as usize)
                .unwrap_or("")
                .to_string()
        }
        fn sort_lines(lines: Vec<String>, field: i32) -> String {
            let mut sorted_lines = lines.clone();
            sorted_lines.sort_by(|a, b| {
                Solution::extract_field(a, field).cmp(&Solution::extract_field(b, field))
            });
            return sorted_lines.join("\n");
        }
    }
    

    Rust details:

    • &str against String. The helper takes &str, a borrowed view of text. In the closure, a is a &String, which Rust converts to &str automatically at the call.
    • Empty fields are real pieces. "a,,c".split(',').nth(1) is Some(""), so unwrap_or isn't even needed for it. The fallback only matters when the position is past the end: "a,b".split(',').nth(5) is None.
    • The cast. (field - 1) as usize is fine for field of 1 or more. A field of 0 would give -1, which as turns into a huge number rather than an error, and then the key is empty. The task starts counting at 1.
    • The reference clones the vector with lines.clone(), although lines is already owned and could be made mutable directly, as in earlier versions. Cloning is harmless here, just an extra copy.
    • The explicit Solution::. extract_field takes no self, so it is called through the type name.

    Complexity

    Time: O(n log n) comparisons for n lines. Each comparison extracts two keys, which scans each line up to the requested field, so it costs time proportional to the line lengths. Space: O(L), where L is the total text length, for the cloned lines and the joined result. The temporary keys are short-lived and each is at most one line long.

    Edge cases and common mistakes

    • Stability. ["b,x", "a,x", "c,w"] with field 2 gives "c,w\nb,x\na,x". The two lines with key x keep their input order, even though a,x would come first if the whole line were compared.
    • Empty keys. ["a,,c", "b,z,a", "c,,b"] with field 2 gives "a,,c\nc,,b\nb,z,a": the empty key sorts first and the two such lines keep their order.
    • Numbers sort as text. ["x,10", "y,9"] keeps x,10 first.
    • Off-by-one. Using field in place of field - 1 picks the wrong piece.
    • Missing field. A line shorter than field, such as "c" with field 2, has the empty key and sorts first. The task promises this won't occur, but the code handles it. For ["a,b", "c"] the result is "c\na,b".
    • Empty list. The result is "".

    Testing

    • ["alice,30", "bob,25", "carol,40"] with field 2 gives "bob,25\nalice,30\ncarol,40".
    • ["b,x", "a,x", "c,w"] with field 2 gives "c,w\nb,x\na,x".
    • ["a,,c", "b,z,a", "c,,b"] with field 2 gives "a,,c\nc,,b\nb,z,a".
    • ["b", "a"] with field 1 gives "a\nb".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free