String
The type of string literal "hello, world" is &str, e.g let s: &str = "hello, world".
Str and &str
- 🌟 We can’t use
strtype in normal ways, but we can use&str.
2. // Fix error without adding new line
3. fn main() {
4. let s: str = "hello, world";
6. println!("Success!");
7. }
- 🌟🌟 We can only use
strby boxing it,&can be used to convertBox<str>to&str
2. // Fix the error with at least two solutions
3. fn main() {
4. let s: Box<str> = "hello, world".into();
5. greetings(s)
6. }
8. fn greetings(s: &str) {
9. println!("{}",s)
10. }
String
String type is defined in std and stored as a vector of bytes (Vec), but guaranteed to always be a valid UTF-8 sequence. String is heap allocated, growable and not null terminated.
- 🌟
2. // Fill the blank
3. fn main() {
4. let mut s = __;
5. s.push_str("hello, world");
6. s.push('!');
8. assert_eq!(s, "hello, world!");
10. println!("Success!");
11. }
- 🌟🌟🌟
2. // Fix all errors without adding newline
3. fn main() {
4. let s = String::from("hello");
5. s.push(',');
6. s.push(" world");
7. s += "!".to_string();
9. println!("{}", s);
10. }
- 🌟🌟
replacecan be used to replace substring
2. // Fill the blank
3. fn main() {
4. let s = String::from("I like dogs");
5. // Allocate new memory and store the modified string there
6. let s1 = s.__("dogs", "cats");
8. assert_eq!(s1, "I like cats");
10. println!("Success!");
11. }
More String methods can be found under String module.
- 🌟🌟 You can only concat a
Stringwith&str, andString‘s ownership can be moved to another variable.
2. // Fix errors without removing any line
3. fn main() {
4. let s1 = String::from("hello,");
5. let s2 = String::from("world!");
6. let s3 = s1 + s2;
7. assert_eq!(s3, "hello,world!");
8. println!("{}", s1);
9. }
&str and String
Opposite to the seldom using of str, &str and String are used everywhere!
- 🌟🌟
&strcan be converted toStringin two ways
2. // Fix error with at least two solutions
3. fn main() {
4. let s = "hello, world";
5. greetings(s)
6. }
8. fn greetings(s: String) {
9. println!("{}", s)
10. }
- 🌟🌟 We can use
String::fromorto_stringto convert a&strtoString
2. // Use two approaches to fix the error and without adding a new line
3. fn main() {
4. let s = "hello, world".to_string();
5. let s1: &str = s;
7. println!("Success!");
8. }
String escapes
- 🌟
1. fn main() {
2. // You can use escapes to write bytes by their hexadecimal values
3. // Fill the blank below to show "I'm writing Rust"
4. let byte_escape = "I'm writing Ru\x73__!";
5. println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);
7. // ...Or Unicode code points.
8. let unicode_codepoint = "\u{211D}";
9. let character_name = "\"DOUBLE-STRUCK CAPITAL R\"";
11. println!("Unicode character {} (U+211D) is called {}",
12. unicode_codepoint, character_name );
14. let long_string = "String literals
15. can span multiple lines.
16. The linebreak and indentation here \
17. can be escaped too!";
18. println!("{}", long_string);
19. }
- 🌟🌟🌟 Sometimes there are just too many characters that need to be escaped or it’s just much more convenient to write a string out as-is. This is where raw string literals come into play.
2. /* Fill in the blank and fix the errors */
3. fn main() {
4. let raw_str = r"Escapes don't work here: \x3F \u{211D}";
5. // Modify above line to make it work
6. assert_eq!(raw_str, "Escapes don't work here: ? ℝ");
8. // If you need quotes in a raw string, add a pair of #s
9. let quotes = r#"And then I said: "There is no escape!""#;
10. println!("{}", quotes);
12. // If you need "# in your string, just use more #s in the delimiter.
13. // You can use up to 65535 #s.
14. let delimiter = r###"A string with "# in it. And even "##!"###;
15. println!("{}", delimiter);
17. // Fill the blank
18. let long_delimiter = __;
19. assert_eq!(long_delimiter, "Hello, \"##\"");
21. println!("Success!");
22. }
Byte string
Want a string that’s not UTF-8? (Remember, str and String must be valid UTF-8). Or maybe you want an array of bytes that’s mostly text? Byte strings to the rescue!
Example:
1. use std::str;
3. fn main() {
4. // Note that this is not actually a `&str`
5. let bytestring: &[u8; 21] = b"this is a byte string";
7. // Byte arrays don't have the `Display` trait, so printing them is a bit limited
8. println!("A byte string: {:?}", bytestring);
10. // Byte strings can have byte escapes...
11. let escaped = b"\x52\x75\x73\x74 as bytes";
12. // ...But no unicode escapes
13. // let escaped = b"\u{211D} Is not allowed";
14. println!("Some escaped bytes: {:?}", escaped);
16. // Raw byte strings work just like raw strings
17. let raw_bytestring = br"\u{211D} is not escaped here";
18. println!("{:?}", raw_bytestring);
20. // Converting a byte array to `str` can fail
21. if let Ok(my_str) = str::from_utf8(raw_bytestring) {
22. println!("And the same as text: '{}'", my_str);
23. }
25. let _quotes = br#"You can also use "fancier" formatting, \
26. like with normal raw strings"#;
28. // Byte strings don't have to be UTF-8
29. let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" In SHIFT-JIS
31. // But then they can't always be converted to `str`
32. match str::from_utf8(shift_jis) {
33. Ok(my_str) => println!("Conversion successful: '{}'", my_str),
34. Err(e) => println!("Conversion failed: {:?}", e),
35. };
36. }
A more detailed listing of the ways to write string literals and escape characters is given in the ‘Tokens’ chapter of the Rust Reference.
String index
- 🌟🌟🌟 You can’t use index to access a char in a string, but you can use slice
&s1[start..end].
2. fn main() {
3. let s1 = String::from("hi,中国");
4. let h = s1[0]; // Modify this line to fix the error, tips: `h` only takes 1 byte in UTF8 format
5. assert_eq!(h, "h");
7. let h1 = &s1[3..5]; // Modify this line to fix the error, tips: `中` takes 3 bytes in UTF8 format
8. assert_eq!(h1, "中");
10. println!("Success!");
11. }
Operate on UTF8 string
- 🌟
2. fn main() {
3. // Fill the blank to print each char in "你好,世界"
4. for c in "你好,世界".__ {
5. println!("{}", c)
6. }
7. }
utf8_slice
You can use utf8_slice to slice UTF8 string, it can index chars instead of bytes.
Example
1. use utf8_slice;
2. fn main() {
3. let s = "The 🚀 goes to the 🌑!";
5. let rocket = utf8_slice::slice(s, 4, 5);
6. // Will equal "🚀"
7. }
You can find the solutions here(under the solutions path), but only use it when you need it
