fn main() {
let b = b"abc\xc3\xa4\xc3\xb6\xc3\xbc";
let s = std::str::from_utf8(&b[0..9]);
println!("Result: {:?}", s);
}
Will get UTF-8 error when slicing only &b[0..6]
.
fn main() {
let s = "abcäöü"; // or with .to_string() as String
let ss = &s[0..9];
println!("Result: {:?}", ss);
}
Will get UTF-8 panic when slicing only &s[0..6]
.
fn main() {
let s = "abcäöü".to_string();
// let c = s[4 as usize]; // not supported because of UTF-8 trouble
let c = s.as_bytes()[4 as usize];
println!("Result: {:x}", c);
}
Indexing into strings is not supported, need to use as_bytes()
.
fn main() {
let s = "abcäöü".to_string();
let c = s.chars().nth(3);
println!("Result: {:?}", c);
}
Can use the iterator provided by chars()
.
fn main() {
let s = "abcäöü".to_string();
for c in s.chars() {
println!("Result: {:?}", c);
}
}
fn main() {
let mut s = String::with_capacity(100);
s = s + "abc";
let t = "xyz".to_string();
// s = s + t; // does not work
s = s + &t; // works!
s.push('X');
// s.push_str(t); // does not work
s.push_str(&t); // works
println!("{}", s);
// let u : String = s + &t; // works, but moves s into u!
let u : String = s.clone() + &t;
println!("{} {}", s, u);
}
If there is enough capacity, there is no reallocation and memory copy.
fn main() {
// Matching:
let s = "abcdefGhijklmnopqrstuvwxyz".to_string();
if s.starts_with("abc") {
println!("starts with abc");
}
if s.ends_with("xyz") {
println!("ends with xyz");
}
// Finding:
let mut pos = s.find("def");
println!("def: {:?}", pos);
pos = s.find('h');
println!("h {:?}", pos);
pos = s.find(char::is_uppercase);
println!("is_uppercase: {:?}", pos);
// Safe slicing:
let r = s.get(6..9);
println!("{:?}", r);
let (a, b) = s.split_at(13);
println!("{}, {}", a, b);
// Splitting:
let x = "abc def ghi".to_string();
let pieces : Vec<&str> = x.split_whitespace().collect();
println!("{:?}", pieces);
let y = "abc\ndef\nghi\n\n".to_string();
let pieces : Vec<&str> = y.lines().collect();
println!("{:?}", pieces);
// Trimming:
let z = " a b c \n";
println!("Trimmed:{}<<<", z.trim());
}
There is more: Repeating strings, replacing substrings, converting to upper or lower case, parsing to another type, ...
- Rust book: https://doc.rust-lang.org/book/ch08-02-strings.html
- Strings: https://doc.rust-lang.org/std/string/struct.String.html
&str
: https://doc.rust-lang.org/std/primitive.str.html- Utilities: https://doc.rust-lang.org/std/str/index.html
- Video: https://youtu.be/joiaS8N71h0
- Overview: https://gist.github.com/max-itzpapalotl/18f7675a60f6f9603250367bcb63992e