HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

Is there a method like JavaScript's substr in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
substrlikemethodrustjavascriptthere

Problem

I looked at the Rust docs for String but I can't find a way to extract a substring.

Is there a method like JavaScript's substr in Rust? If not, how would you implement it?

str.substr(start[, length])


The closest is probably slice_unchecked but it uses byte offsets instead of character indexes and is marked unsafe.

Solution

For characters, you can use s.chars().skip(pos).take(len):

fn main() {
    let s = "Hello, world!";
    let ss: String = s.chars().skip(7).take(5).collect();
    println!("{}", ss);
}


Beware of the definition of Unicode characters though.

For bytes, you can use the slice syntax:

fn main() {
    let s = b"Hello, world!";
    let ss = &s[7..12];
    println!("{:?}", ss);
}

Code Snippets

fn main() {
    let s = "Hello, world!";
    let ss: String = s.chars().skip(7).take(5).collect();
    println!("{}", ss);
}
fn main() {
    let s = b"Hello, world!";
    let ss = &s[7..12];
    println!("{:?}", ss);
}

Context

Stack Overflow Q#37157926, score: 85

Revisions (0)

No revisions yet.