Rust : String and chart set and code type

zhangwuji

Zhangwuji

Posted on May 21, 2024

Rust : String and chart set and code type

1.
how to splice multiple string types?

 let s1 = String::from("Hello");
 let s2 = String::from("World");
 let s3 = s1 + &s2;

Enter fullscreen mode Exit fullscreen mode

s1 will be destroied in this way。 So this way is not recommonded。

  let s1 = String::from("Hello");
  let s2 = String::from("World");
  let s3 = s1.clone() + &s2;
Enter fullscreen mode Exit fullscreen mode

this way is so complicated,let us see it's simple way;

        let mut s1 = String::from("Hello");
        let s2 = String::from("World");
        let s3 = format!("========={}{}", s1, s2);
Enter fullscreen mode Exit fullscreen mode

2.
rust string use unicode character set,and the rule of encode and
decode useing utf-8, So the string's every char may be occupy
different numer of bytes。

     let s1 = String::from("नमस्ते");
     println!("{}",s1.len())

       let s1 = String::from("智");
       println!("{}",s1.len()) ;

      let s1 = String::from("123");
       println!("{}",s1.len()) ;

Enter fullscreen mode Exit fullscreen mode

you will find different char; they occupy different number of bytes。

 let s1 = String::from("नमस्ते");
let s2= &s1[2..5];
Enter fullscreen mode Exit fullscreen mode

remember this index is in the string splice'process is bytes index.

let start_byte = s.char_indices().nth(start).map(|(i, _)| i).unwrap_or(s.len());

let end_bytes = s.char_indices().nth(start).map(|(i, _)| i).unwrap_or(s.len());

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
zhangwuji
Zhangwuji

Posted on May 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related