Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a vector of Strings alphabetically? [duplicate]

Tags:

rust

I want to order a Strings vector alphabetically

fn main() {
    let mut vec = Vec::new();
    vec.push("richard");
    vec.push("charles");
    vec.push("Peter");
    println!("{:?}", vec);
}

I tried println!("{:?}", vec.sort()); and println!("{}", vec.sort_by(|a,b| b.cmp(a))); and both response is ().

And I expect the following result

["charles", "Peter", "richard"]
like image 313
Ricardo Prieto Avatar asked Apr 22 '19 03:04

Ricardo Prieto


People also ask

How do you order a string in alphabetical order?

Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.

Can you sort a vector string?

Approach: The sort() function in C++ STL is able to sort vector of strings if and only if it contains single numeric character for example, { '1', ' '} but to sort numeric vector of string with multiple character for example, {'12', '56', '14' } one should write own comparator inside sort() function.

How do you sort a vector alphabetically or numerically?

To sort a vector alphabetically in R using the sort() function that takes a vector as an argument and returns an alphabetically ordered value for the character vector and ascending order for numeric. Use c() function to create vector. To sort vectors by descending order use decreasing=TRUE param.


1 Answers

sort function is defined on slices (and on Vecs, as they can Deref to slices) as pub fn sort(&mut self), i.e. it performs sorting in place, mutating the existing piece of data. So to achieve what you're trying to do, you can try the following:

fn main() {
    let mut vec = Vec::new();
    vec.push("richard");
    vec.push("charles");
    vec.push("Peter");
    vec.sort();
    println!("{:?}", vec);
}

Unhappily, this isn't quite the thing you want, since this will sort "Peter" before "charles" - the default comparator of strings is case-sensitive (in fact, it's even locale-agnostic, since it compares basing on Unicode code points). So, if you want to perform case-insensitive sorting, here's the modification:

fn main() {
    let mut vec = Vec::new();
    vec.push("richard");
    vec.push("charles");
    vec.push("Peter");
    vec.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()));
    println!("{:?}", vec);
}
like image 68
Cerberus Avatar answered Sep 23 '22 04:09

Cerberus