Find next char boundary index in string after char -


given string s, , index i character starts:

let s = "abc 好 def"; let = 4; 

what's best way index after character, can slice string , abc 好? in code:

let end = find_end(s, i); assert_eq!("abc 好", &s[0..end]); 

(note, + 1 doesn't work because assumes character 1 byte long.)

i have following:

fn find_end(s: &str, i: usize) -> usize {     + s[i..].chars().next().unwrap().len_utf8() } 

but i'm wondering if i'm missing , there's better way?

you use char_indices next index rather using len_utf8 on character, though has special case last character.

i use handy str::is_char_boundary() method. here's implementation using that:

fn find_end(s: &str, i: usize) -> usize {     assert!(i < s.len());     let mut end = i+1;     while !s.is_char_boundary(end) {         end += 1;     }     end } 

playground link

normally make such function return option<usize> in case it's called index @ end of s, i've asserted.

in many cases, instead of explicitly calling find_end may make sense iterate using char_indices, gives each index along characters; though it's annoying if want know end of current character.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -