What is the best way to read a position of string?

Hi, What is the best way to read a position of string?. Thanks.

Do you mean, find a substring? If so, string.find(substring).

Or maybe you just want to index a string?

fn main() {
    let s = "some str you like to index";
    
    // index a single position
    assert_eq!(&s[..1], "s");
    assert_eq!(&s[1..2], "o");
    assert_eq!(&s[2..3], "m");
    assert_eq!(&s[3..4], "e");
    
    // get a single char (note the single quotes '.' around chars)
    assert_eq!(s.chars().nth(0).unwrap(), 's');
    assert_eq!(s.chars().nth(1).unwrap(), 'o');
    assert_eq!(s.chars().nth(2).unwrap(), 'm');
    assert_eq!(s.chars().nth(3).unwrap(), 'e');
    
    // index a subslice
    assert_eq!(&s[..4], "some");
    assert_eq!(&s[5..8], "str");
    assert_eq!(&s[9..12], "you");
    assert_eq!(&s[13..17], "like");
    assert_eq!(&s[18..20], "to");
    assert_eq!(&s[21..], "index");
}

Playground.

Quick reminder that direct indexing only works on ASCII-only strings. This is indexing into bytes not chars.

2 Likes

You are right, I should've clarified that in my answer.

let s = "ö";
        
// (!) this panics, because "ö" takes up two bytes
assert_eq!(&s[..1], "ö");

// this works
assert_eq!(&s[..2], "ö");

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.