How to remove first and last character of a string in Rust?
Asked Answered
K

4

47

I'm wondering how I can remove the first and last character of a string in Rust.

Example:

Input:

"Hello World"

Output:

"ello Worl"

Koger answered 31/1, 2021 at 6:39 Comment(2)
What have you tried so far?Landtag
I got it, after trying, I'll post an answerKoger
I
56

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.

Intangible answered 31/1, 2021 at 7:13 Comment(3)
This is my favourite answer because it works with multi-byte characters and empty strings.Koger
As always when playing with unicode, it is worth remembering the difference between characters and grapheme clusters. For example, there are cases where this will remove an accent on the last glyph or change a compound emoji, rather than removing the whole cluster. So while this gives what the OP asks for, it may not actually be what they want. (More a warning for the OP, than a criticism of this answer - properly handling grapheme clusters is tricky and non-trivial)Hamstring
@MichaelAnderson Absolutely! I never know how in-depth to go with unicode handling. For more complicated glyphs and emojis, swapping .chars() to .graphemes(true) from the unicode segmentation crate may be necessary.Intangible
M
30

…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
}
Mckellar answered 5/1, 2022 at 19:20 Comment(2)
Worth noting that remove is an O(n) operation.Darleen
@Sarkar Correct – but it doesn't result in a memory allocation.Mckellar
K
21

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.

Koger answered 31/1, 2021 at 6:49 Comment(4)
What happens if the string is empty? will the program crash?Peel
I could add an if statement: if string.is_empty() { "" }Koger
I think this would also work &string[1..];Seductress
Warning: this code will only work for ASCII characters, where 1 char = 1 byte. If your string starts/ends with a UTF-8 character represented by 2 or more bytes, the code will panic.Deidradeidre
E
-2

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];
Emphasis answered 12/5 at 13:1 Comment(1)
What does this add over this answer (which is also wrong because it doesn't account for Unicode)?Bangtail

© 2022 - 2024 — McMap. All rights reserved.