Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

50.11.1Splitting a string

The split_whitespace() splits a string on white spaces and returns an iterator on the sub-strings:

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):

ab
cde
f
ghi
jk
l
()

50.11.2Iterating over a string

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:

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:

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():

()

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:

abc
def
ghi
()

50.11.5Strings in struct

We define the Book structure with the two fields title and author as String instances:

When defining the new() constructor, we move the arguments title and author into the new String instance:

One way to implement the access methods of the two string fields title and author, is to return clones:

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):

("Robinson Crusoe", "Daniel Defoe", 1719)