50.11.1Splitting a string¶
The split_whitespace() splits a string on white spaces and returns an
iterator on the sub-strings:
let n = "a b c d e f";
for s in n.split_whitespace() {
println!("{s}")
}a
b
c
d
e
f
()The more generic split() method does the same on a pattern (e.g.: a
string, a character, a function or a closure):
let n = "ab..cde..f..ghi..jk..l";
for s in n.split("..") {
println!("{s}")
}ab
cde
f
ghi
jk
l
()50.11.2Iterating over a string¶
let s = "Салам";
println!("Iterating over the characters:");
for c in s.chars() {
print!("{c}, ");
}
println!();
println!("Iterating over the bytes:");
for b in s.bytes() {
print!("{b}, ");
}Iterating over the characters:
С, а, л, а, м,
Iterating over the bytes:
()Each character is defined by more than one byte.
50.11.3Searching into a string¶
We define the original string in which to search for lowercase characters:
let s = "AbCDeFGHijkL";We define a new slice variable, mutable, that we will use to store a reference (i.e.: slice) to the remaining string part to search:
let mut t = s;We loop on the results of the find() method, which is called with the
predicate char::is_lowercase to find the next lowercase character.
During the loop, we update the slice variable t in order for it to be
ready for next call to find():
while let Some(i) = t.find(char::is_lowercase) {
print!("{}", &t[i..i+1]);
t = &t[i+1..];
}()50.11.4Vector of strings¶
We create an empty vector, specifying that it will hold String
values. We push the three strings into the vector, then loop on its
elements by references and print each string:
let mut v: Vec<String> = Vec::new();
v.push(String::from("abc"));
v.push(String::from("def"));
v.push(String::from("ghi"));
for s in &v {
println!("{s}");
}abc
def
ghi
()50.11.5Strings in struct¶
We define the Book structure with the two fields title and author
as String instances:
struct Book {
title: String,
author: String,
year: i16,
}When defining the new() constructor, we move the arguments title
and author into the new String instance:
impl Book {
fn new(title: String, author: String, year: i16) -> Self {
Self {
title,
author,
year,
}
}
}One way to implement the access methods of the two string fields
title and author, is to return clones:
impl Book {
fn title(&self) -> String {
self.title.clone()
}
fn author(&self) -> String {
self.author.clone()
}
}However, this would create a new object each time we want to access a field’s value. This is not optimal, since most of the time we just want to read the value, not modify it. A better approach is to return string slices (see Slices) that will be valid during the whole lifetime of the Book instance (see Lifetimes):
impl Book {
fn title(&self) -> &str {
&self.title
}
fn author(&self) -> &str {
&self.author
}
}impl Book {
fn year(&self) -> i16 {
self.year
}
}let book = Book::new("Robinson Crusoe".to_string(), "Daniel Defoe".to_string(),
1719);
(book.title(), book.author(), book.year())("Robinson Crusoe", "Daniel Defoe", 1719)