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"]
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.
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.
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.
sort
function is defined on slices (and on Vec
s, 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With