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

前端 未结 7 1095
天命终不由人
天命终不由人 2021-02-02 10:21

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

相关标签:
7条回答
  • 2021-02-02 11:10

    For my_string.substring(start, len)-like syntax, you can write a custom trait:

    trait StringUtils {
        fn substring(&self, start: usize, len: usize) -> Self;
    }
    
    impl StringUtils for String {
        fn substring(&self, start: usize, len: usize) -> Self {
            self.chars().skip(start).take(len).collect()
        }
    }
    
    // Usage:
    fn main() {
        let phrase: String = "this is a string".to_string();
        println!("{}", phrase.substring(5, 8)); // prints "is a str"
    }
    
    0 讨论(0)
提交回复
热议问题