I'm wondering how I can remove the first and last character of a string in Rust.
Example:
Input:
"Hello World"
Output:
"ello Worl"
I'm wondering how I can remove the first and last character of a string in Rust.
Example:
Input:
"Hello World"
Output:
"ello Worl"
You can use the .chars()
iterator and ignore the first and last characters:
fn rem_first_and_last(value: &str) -> &str {
let mut chars = value.chars();
chars.next();
chars.next_back();
chars.as_str()
}
It returns an empty string for zero- or one-sized strings and it will handle multi-byte unicode characters correctly. See it working on the playground.
.chars()
to .graphemes(true)
from the unicode segmentation crate may be necessary. –
Intangible …or the trivial solution
also works with Unicode characters:
let mut s = "Hello World".to_string();
s.pop(); // remove last
if s.len() > 0 {
s.remove(0); // remove first
}
O(n)
operation. –
Darleen I did this by using string slices.
fn main() {
let string: &str = "Hello World";
let first_last_off: &str = &string[1..string.len() - 1];
println!("{}", first_last_off);
}
I took all the characters in the string until the end of the string - 1.
if string.is_empty() { "" }
–
Koger &string[1..];
–
Seductress I recommend to use slices and convert to the desired type:
let hi: String = String::from("Hello, World");
// if hi.len() == 0 it will crash
if hi.len() == 0 {
// handle error ..
}
let stripped_string: String = hi[1..hi.len()-1].to_string();
let stripped_str: &str = &hi[1..hi.len()-1];
© 2022 - 2024 — McMap. All rights reserved.