413 lines
27 KiB
HTML
413 lines
27 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Storing UTF-8 Encoded Text with Strings</title>
|
||
</head>
|
||
<body>
|
||
<h2 id="storing-utf-8-encoded-text-with-strings"><a class="header" href="#storing-utf-8-encoded-text-with-strings">Storing UTF-8 Encoded Text with Strings</a></h2>
|
||
<p>We talked about strings in Chapter 4, but we’ll look at them in more depth now.
|
||
New Rustaceans commonly get stuck on strings for a combination of three
|
||
reasons: Rust’s propensity for exposing possible errors, strings being a more
|
||
complicated data structure than many programmers give them credit for, and
|
||
UTF-8. These factors combine in a way that can seem difficult when you’re
|
||
coming from other programming languages.</p>
|
||
<p>We discuss strings in the context of collections because strings are
|
||
implemented as a collection of bytes, plus some methods to provide useful
|
||
functionality when those bytes are interpreted as text. In this section, we’ll
|
||
talk about the operations on <code>String</code> that every collection type has, such as
|
||
creating, updating, and reading. We’ll also discuss the ways in which <code>String</code>
|
||
is different from the other collections, namely, how indexing into a <code>String</code> is
|
||
complicated by the differences between how people and computers interpret
|
||
<code>String</code> data.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="what-is-a-string"></a></p>
|
||
<h3 id="defining-strings"><a class="header" href="#defining-strings">Defining Strings</a></h3>
|
||
<p>We’ll first define what we mean by the term <em>string</em>. Rust has only one string
|
||
type in the core language, which is the string slice <code>str</code> that is usually seen
|
||
in its borrowed form, <code>&str</code>. In Chapter 4, we talked about string slices,
|
||
which are references to some UTF-8 encoded string data stored elsewhere. String
|
||
literals, for example, are stored in the program’s binary and are therefore
|
||
string slices.</p>
|
||
<p>The <code>String</code> type, which is provided by Rust’s standard library rather than
|
||
coded into the core language, is a growable, mutable, owned, UTF-8 encoded
|
||
string type. When Rustaceans refer to “strings” in Rust, they might be
|
||
referring to either the <code>String</code> or the string slice <code>&str</code> types, not just one
|
||
of those types. Although this section is largely about <code>String</code>, both types are
|
||
used heavily in Rust’s standard library, and both <code>String</code> and string slices
|
||
are UTF-8 encoded.</p>
|
||
<h3 id="creating-a-new-string"><a class="header" href="#creating-a-new-string">Creating a New String</a></h3>
|
||
<p>Many of the same operations available with <code>Vec<T></code> are available with <code>String</code>
|
||
as well because <code>String</code> is actually implemented as a wrapper around a vector
|
||
of bytes with some extra guarantees, restrictions, and capabilities. An example
|
||
of a function that works the same way with <code>Vec<T></code> and <code>String</code> is the <code>new</code>
|
||
function to create an instance, shown in Listing 8-11.</p>
|
||
<figure class="listing" id="listing-8-11">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let mut s = String::new();
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-11">Listing 8-11</a>: Creating a new, empty <code>String</code></figcaption>
|
||
</figure>
|
||
<p>This line creates a new, empty string called <code>s</code>, into which we can then load
|
||
data. Often, we’ll have some initial data with which we want to start the
|
||
string. For that, we use the <code>to_string</code> method, which is available on any type
|
||
that implements the <code>Display</code> trait, as string literals do. Listing 8-12 shows
|
||
two examples.</p>
|
||
<figure class="listing" id="listing-8-12">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let data = "initial contents";
|
||
|
||
let s = data.to_string();
|
||
|
||
// The method also works on a literal directly:
|
||
let s = "initial contents".to_string();
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-12">Listing 8-12</a>: Using the <code>to_string</code> method to create a <code>String</code> from a string literal</figcaption>
|
||
</figure>
|
||
<p>This code creates a string containing <code>initial contents</code>.</p>
|
||
<p>We can also use the function <code>String::from</code> to create a <code>String</code> from a string
|
||
literal. The code in Listing 8-13 is equivalent to the code in Listing 8-12
|
||
that uses <code>to_string</code>.</p>
|
||
<figure class="listing" id="listing-8-13">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let s = String::from("initial contents");
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-13">Listing 8-13</a>: Using the <code>String::from</code> function to create a <code>String</code> from a string literal</figcaption>
|
||
</figure>
|
||
<p>Because strings are used for so many things, we can use many different generic
|
||
APIs for strings, providing us with a lot of options. Some of them can seem
|
||
redundant, but they all have their place! In this case, <code>String::from</code> and
|
||
<code>to_string</code> do the same thing, so which one you choose is a matter of style and
|
||
readability.</p>
|
||
<p>Remember that strings are UTF-8 encoded, so we can include any properly encoded
|
||
data in them, as shown in Listing 8-14.</p>
|
||
<figure class="listing" id="listing-8-14">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let hello = String::from("السلام عليكم");
|
||
let hello = String::from("Dobrý den");
|
||
let hello = String::from("Hello");
|
||
let hello = String::from("שלום");
|
||
let hello = String::from("नमस्ते");
|
||
let hello = String::from("こんにちは");
|
||
let hello = String::from("안녕하세요");
|
||
let hello = String::from("你好");
|
||
let hello = String::from("Olá");
|
||
let hello = String::from("Здравствуйте");
|
||
let hello = String::from("Hola");
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-14">Listing 8-14</a>: Storing greetings in different languages in strings</figcaption>
|
||
</figure>
|
||
<p>All of these are valid <code>String</code> values.</p>
|
||
<h3 id="updating-a-string"><a class="header" href="#updating-a-string">Updating a String</a></h3>
|
||
<p>A <code>String</code> can grow in size and its contents can change, just like the contents
|
||
of a <code>Vec<T></code>, if you push more data into it. In addition, you can conveniently
|
||
use the <code>+</code> operator or the <code>format!</code> macro to concatenate <code>String</code> values.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="appending-to-a-string-with-push_str-and-push"></a></p>
|
||
<h4 id="appending-with-push_str-or-push"><a class="header" href="#appending-with-push_str-or-push">Appending with <code>push_str</code> or <code>push</code></a></h4>
|
||
<p>We can grow a <code>String</code> by using the <code>push_str</code> method to append a string slice,
|
||
as shown in Listing 8-15.</p>
|
||
<figure class="listing" id="listing-8-15">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let mut s = String::from("foo");
|
||
s.push_str("bar");
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-15">Listing 8-15</a>: Appending a string slice to a <code>String</code> using the <code>push_str</code> method</figcaption>
|
||
</figure>
|
||
<p>After these two lines, <code>s</code> will contain <code>foobar</code>. The <code>push_str</code> method takes a
|
||
string slice because we don’t necessarily want to take ownership of the
|
||
parameter. For example, in the code in Listing 8-16, we want to be able to use
|
||
<code>s2</code> after appending its contents to <code>s1</code>.</p>
|
||
<figure class="listing" id="listing-8-16">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let mut s1 = String::from("foo");
|
||
let s2 = "bar";
|
||
s1.push_str(s2);
|
||
println!("s2 is {s2}");
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-16">Listing 8-16</a>: Using a string slice after appending its contents to a <code>String</code></figcaption>
|
||
</figure>
|
||
<p>If the <code>push_str</code> method took ownership of <code>s2</code>, we wouldn’t be able to print
|
||
its value on the last line. However, this code works as we’d expect!</p>
|
||
<p>The <code>push</code> method takes a single character as a parameter and adds it to the
|
||
<code>String</code>. Listing 8-17 adds the letter <em>l</em> to a <code>String</code> using the <code>push</code>
|
||
method.</p>
|
||
<figure class="listing" id="listing-8-17">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let mut s = String::from("lo");
|
||
s.push('l');
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-17">Listing 8-17</a>: Adding one character to a <code>String</code> value using <code>push</code></figcaption>
|
||
</figure>
|
||
<p>As a result, <code>s</code> will contain <code>lol</code>.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="concatenation-with-the--operator-or-the-format-macro"></a></p>
|
||
<h4 id="concatenating-with--or-format"><a class="header" href="#concatenating-with--or-format">Concatenating with <code>+</code> or <code>format!</code></a></h4>
|
||
<p>Often, you’ll want to combine two existing strings. One way to do so is to use
|
||
the <code>+</code> operator, as shown in Listing 8-18.</p>
|
||
<figure class="listing" id="listing-8-18">
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let s1 = String::from("Hello, ");
|
||
let s2 = String::from("world!");
|
||
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-18">Listing 8-18</a>: Using the <code>+</code> operator to combine two <code>String</code> values into a new <code>String</code> value</figcaption>
|
||
</figure>
|
||
<p>The string <code>s3</code> will contain <code>Hello, world!</code>. The reason <code>s1</code> is no longer
|
||
valid after the addition, and the reason we used a reference to <code>s2</code>, has to do
|
||
with the signature of the method that’s called when we use the <code>+</code> operator.
|
||
The <code>+</code> operator uses the <code>add</code> method, whose signature looks something like
|
||
this:</p>
|
||
<pre><code class="language-rust ignore">fn add(self, s: &str) -> String {</code></pre>
|
||
<p>In the standard library, you’ll see <code>add</code> defined using generics and associated
|
||
types. Here, we’ve substituted in concrete types, which is what happens when we
|
||
call this method with <code>String</code> values. We’ll discuss generics in Chapter 10.
|
||
This signature gives us the clues we need in order to understand the tricky
|
||
bits of the <code>+</code> operator.</p>
|
||
<p>First, <code>s2</code> has an <code>&</code>, meaning that we’re adding a reference of the second
|
||
string to the first string. This is because of the <code>s</code> parameter in the <code>add</code>
|
||
function: We can only add a string slice to a <code>String</code>; we can’t add two
|
||
<code>String</code> values together. But wait—the type of <code>&s2</code> is <code>&String</code>, not <code>&str</code>,
|
||
as specified in the second parameter to <code>add</code>. So, why does Listing 8-18
|
||
compile?</p>
|
||
<p>The reason we’re able to use <code>&s2</code> in the call to <code>add</code> is that the compiler
|
||
can coerce the <code>&String</code> argument into a <code>&str</code>. When we call the <code>add</code> method,
|
||
Rust uses a deref coercion, which here turns <code>&s2</code> into <code>&s2[..]</code>. We’ll
|
||
discuss deref coercion in more depth in Chapter 15. Because <code>add</code> does not take
|
||
ownership of the <code>s</code> parameter, <code>s2</code> will still be a valid <code>String</code> after this
|
||
operation.</p>
|
||
<p>Second, we can see in the signature that <code>add</code> takes ownership of <code>self</code>
|
||
because <code>self</code> does <em>not</em> have an <code>&</code>. This means <code>s1</code> in Listing 8-18 will be
|
||
moved into the <code>add</code> call and will no longer be valid after that. So, although
|
||
<code>let s3 = s1 + &s2;</code> looks like it will copy both strings and create a new one,
|
||
this statement actually takes ownership of <code>s1</code>, appends a copy of the contents
|
||
of <code>s2</code>, and then returns ownership of the result. In other words, it looks
|
||
like it’s making a lot of copies, but it isn’t; the implementation is more
|
||
efficient than copying.</p>
|
||
<p>If we need to concatenate multiple strings, the behavior of the <code>+</code> operator
|
||
gets unwieldy:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let s1 = String::from("tic");
|
||
let s2 = String::from("tac");
|
||
let s3 = String::from("toe");
|
||
|
||
let s = s1 + "-" + &s2 + "-" + &s3;
|
||
<span class="boring">}</span></code></pre>
|
||
<p>At this point, <code>s</code> will be <code>tic-tac-toe</code>. With all of the <code>+</code> and <code>"</code>
|
||
characters, it’s difficult to see what’s going on. For combining strings in
|
||
more complicated ways, we can instead use the <code>format!</code> macro:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span> let s1 = String::from("tic");
|
||
let s2 = String::from("tac");
|
||
let s3 = String::from("toe");
|
||
|
||
let s = format!("{s1}-{s2}-{s3}");
|
||
<span class="boring">}</span></code></pre>
|
||
<p>This code also sets <code>s</code> to <code>tic-tac-toe</code>. The <code>format!</code> macro works like
|
||
<code>println!</code>, but instead of printing the output to the screen, it returns a
|
||
<code>String</code> with the contents. The version of the code using <code>format!</code> is much
|
||
easier to read, and the code generated by the <code>format!</code> macro uses references
|
||
so that this call doesn’t take ownership of any of its parameters.</p>
|
||
<h3 id="indexing-into-strings"><a class="header" href="#indexing-into-strings">Indexing into Strings</a></h3>
|
||
<p>In many other programming languages, accessing individual characters in a
|
||
string by referencing them by index is a valid and common operation. However,
|
||
if you try to access parts of a <code>String</code> using indexing syntax in Rust, you’ll
|
||
get an error. Consider the invalid code in Listing 8-19.</p>
|
||
<figure class="listing" id="listing-8-19">
|
||
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
|
||
</span> let s1 = String::from("hi");
|
||
let h = s1[0];
|
||
<span class="boring">}</span></code></pre>
|
||
<figcaption><a href="#listing-8-19">Listing 8-19</a>: Attempting to use indexing syntax with a <code>String</code></figcaption>
|
||
</figure>
|
||
<p>This code will result in the following error:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling collections v0.1.0 (file:///projects/collections)
|
||
error[E0277]: the type `str` cannot be indexed by `{integer}`
|
||
--> src/main.rs:3:16
|
||
|
|
||
3 | let h = s1[0];
|
||
| ^ string indices are ranges of `usize`
|
||
|
|
||
= help: the trait `SliceIndex<str>` is not implemented for `{integer}`
|
||
= note: you can use `.chars().nth()` or `.bytes().nth()`
|
||
for more information, see chapter 8 in The Book: <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>
|
||
= help: the following other types implement trait `SliceIndex<T>`:
|
||
`usize` implements `SliceIndex<ByteStr>`
|
||
`usize` implements `SliceIndex<[T]>`
|
||
= note: required for `String` to implement `Index<{integer}>`
|
||
|
||
For more information about this error, try `rustc --explain E0277`.
|
||
error: could not compile `collections` (bin "collections") due to 1 previous error
|
||
</code></pre>
|
||
<p>The error tells the story: Rust strings don’t support indexing. But why not? To
|
||
answer that question, we need to discuss how Rust stores strings in memory.</p>
|
||
<h4 id="internal-representation"><a class="header" href="#internal-representation">Internal Representation</a></h4>
|
||
<p>A <code>String</code> is a wrapper over a <code>Vec<u8></code>. Let’s look at some of our properly
|
||
encoded UTF-8 example strings from Listing 8-14. First, this one:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span><span class="boring"> let hello = String::from("السلام عليكم");
|
||
</span><span class="boring"> let hello = String::from("Dobrý den");
|
||
</span><span class="boring"> let hello = String::from("Hello");
|
||
</span><span class="boring"> let hello = String::from("שלום");
|
||
</span><span class="boring"> let hello = String::from("नमस्ते");
|
||
</span><span class="boring"> let hello = String::from("こんにちは");
|
||
</span><span class="boring"> let hello = String::from("안녕하세요");
|
||
</span><span class="boring"> let hello = String::from("你好");
|
||
</span><span class="boring"> let hello = String::from("Olá");
|
||
</span><span class="boring"> let hello = String::from("Здравствуйте");
|
||
</span> let hello = String::from("Hola");
|
||
<span class="boring">}</span></code></pre>
|
||
<p>In this case, <code>len</code> will be <code>4</code>, which means the vector storing the string
|
||
<code>"Hola"</code> is 4 bytes long. Each of these letters takes 1 byte when encoded in
|
||
UTF-8. The following line, however, may surprise you (note that this string
|
||
begins with the capital Cyrillic letter <em>Ze</em>, not the number 3):</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||
</span><span class="boring"> let hello = String::from("السلام عليكم");
|
||
</span><span class="boring"> let hello = String::from("Dobrý den");
|
||
</span><span class="boring"> let hello = String::from("Hello");
|
||
</span><span class="boring"> let hello = String::from("שלום");
|
||
</span><span class="boring"> let hello = String::from("नमस्ते");
|
||
</span><span class="boring"> let hello = String::from("こんにちは");
|
||
</span><span class="boring"> let hello = String::from("안녕하세요");
|
||
</span><span class="boring"> let hello = String::from("你好");
|
||
</span><span class="boring"> let hello = String::from("Olá");
|
||
</span> let hello = String::from("Здравствуйте");
|
||
<span class="boring"> let hello = String::from("Hola");
|
||
</span><span class="boring">}</span></code></pre>
|
||
<p>If you were asked how long the string is, you might say 12. In fact, Rust’s
|
||
answer is 24: That’s the number of bytes it takes to encode “Здравствуйте” in
|
||
UTF-8, because each Unicode scalar value in that string takes 2 bytes of
|
||
storage. Therefore, an index into the string’s bytes will not always correlate
|
||
to a valid Unicode scalar value. To demonstrate, consider this invalid Rust
|
||
code:</p>
|
||
<pre><code class="language-rust ignore does_not_compile">let hello = "Здравствуйте";
|
||
let answer = &hello[0];</code></pre>
|
||
<p>You already know that <code>answer</code> will not be <code>З</code>, the first letter. When encoded
|
||
in UTF-8, the first byte of <code>З</code> is <code>208</code> and the second is <code>151</code>, so it would
|
||
seem that <code>answer</code> should in fact be <code>208</code>, but <code>208</code> is not a valid character
|
||
on its own. Returning <code>208</code> is likely not what a user would want if they asked
|
||
for the first letter of this string; however, that’s the only data that Rust
|
||
has at byte index 0. Users generally don’t want the byte value returned, even
|
||
if the string contains only Latin letters: If <code>&"hi"[0]</code> were valid code that
|
||
returned the byte value, it would return <code>104</code>, not <code>h</code>.</p>
|
||
<p>The answer, then, is that to avoid returning an unexpected value and causing
|
||
bugs that might not be discovered immediately, Rust doesn’t compile this code
|
||
at all and prevents misunderstandings early in the development process.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="bytes-and-scalar-values-and-grapheme-clusters-oh-my"></a></p>
|
||
<h4 id="bytes-scalar-values-and-grapheme-clusters"><a class="header" href="#bytes-scalar-values-and-grapheme-clusters">Bytes, Scalar Values, and Grapheme Clusters</a></h4>
|
||
<p>Another point about UTF-8 is that there are actually three relevant ways to
|
||
look at strings from Rust’s perspective: as bytes, scalar values, and grapheme
|
||
clusters (the closest thing to what we would call <em>letters</em>).</p>
|
||
<p>If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is
|
||
stored as a vector of <code>u8</code> values that looks like this:</p>
|
||
<pre><code class="language-text">[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
|
||
224, 165, 135]
|
||
</code></pre>
|
||
<p>That’s 18 bytes and is how computers ultimately store this data. If we look at
|
||
them as Unicode scalar values, which are what Rust’s <code>char</code> type is, those
|
||
bytes look like this:</p>
|
||
<pre><code class="language-text">['न', 'म', 'स', '्', 'त', 'े']
|
||
</code></pre>
|
||
<p>There are six <code>char</code> values here, but the fourth and sixth are not letters:
|
||
They’re diacritics that don’t make sense on their own. Finally, if we look at
|
||
them as grapheme clusters, we’d get what a person would call the four letters
|
||
that make up the Hindi word:</p>
|
||
<pre><code class="language-text">["न", "म", "स्", "ते"]
|
||
</code></pre>
|
||
<p>Rust provides different ways of interpreting the raw string data that computers
|
||
store so that each program can choose the interpretation it needs, no matter
|
||
what human language the data is in.</p>
|
||
<p>A final reason Rust doesn’t allow us to index into a <code>String</code> to get a
|
||
character is that indexing operations are expected to always take constant time
|
||
(O(1)). But it isn’t possible to guarantee that performance with a <code>String</code>,
|
||
because Rust would have to walk through the contents from the beginning to the
|
||
index to determine how many valid characters there were.</p>
|
||
<h3 id="slicing-strings"><a class="header" href="#slicing-strings">Slicing Strings</a></h3>
|
||
<p>Indexing into a string is often a bad idea because it’s not clear what the
|
||
return type of the string-indexing operation should be: a byte value, a
|
||
character, a grapheme cluster, or a string slice. If you really need to use
|
||
indices to create string slices, therefore, Rust asks you to be more specific.</p>
|
||
<p>Rather than indexing using <code>[]</code> with a single number, you can use <code>[]</code> with a
|
||
range to create a string slice containing particular bytes:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>let hello = "Здравствуйте";
|
||
|
||
let s = &hello[0..4];
|
||
<span class="boring">}</span></code></pre>
|
||
<p>Here, <code>s</code> will be a <code>&str</code> that contains the first 4 bytes of the string.
|
||
Earlier, we mentioned that each of these characters was 2 bytes, which means
|
||
<code>s</code> will be <code>Зд</code>.</p>
|
||
<p>If we were to try to slice only part of a character’s bytes with something like
|
||
<code>&hello[0..1]</code>, Rust would panic at runtime in the same way as if an invalid
|
||
index were accessed in a vector:</p>
|
||
<pre><code class="language-console">$ cargo run
|
||
Compiling collections v0.1.0 (file:///projects/collections)
|
||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.43s
|
||
Running `target/debug/collections`
|
||
|
||
thread 'main' panicked at src/main.rs:4:19:
|
||
byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`
|
||
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
|
||
</code></pre>
|
||
<p>You should use caution when creating string slices with ranges, because doing
|
||
so can crash your program.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="methods-for-iterating-over-strings"></a></p>
|
||
<h3 id="iterating-over-strings"><a class="header" href="#iterating-over-strings">Iterating Over Strings</a></h3>
|
||
<p>The best way to operate on pieces of strings is to be explicit about whether
|
||
you want characters or bytes. For individual Unicode scalar values, use the
|
||
<code>chars</code> method. Calling <code>chars</code> on “Зд” separates out and returns two values of
|
||
type <code>char</code>, and you can iterate over the result to access each element:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>for c in "Зд".chars() {
|
||
println!("{c}");
|
||
}
|
||
<span class="boring">}</span></code></pre>
|
||
<p>This code will print the following:</p>
|
||
<pre><code class="language-text">З
|
||
д
|
||
</code></pre>
|
||
<p>Alternatively, the <code>bytes</code> method returns each raw byte, which might be
|
||
appropriate for your domain:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>for b in "Зд".bytes() {
|
||
println!("{b}");
|
||
}
|
||
<span class="boring">}</span></code></pre>
|
||
<p>This code will print the 4 bytes that make up this string:</p>
|
||
<pre><code class="language-text">208
|
||
151
|
||
208
|
||
180
|
||
</code></pre>
|
||
<p>But be sure to remember that valid Unicode scalar values may be made up of more
|
||
than 1 byte.</p>
|
||
<p>Getting grapheme clusters from strings, as with the Devanagari script, is
|
||
complex, so this functionality is not provided by the standard library. Crates
|
||
are available on <a href="https://crates.io/">crates.io</a><!-- ignore --> if this is the
|
||
functionality you need.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="strings-are-not-so-simple"></a></p>
|
||
<h3 id="handling-the-complexities-of-strings"><a class="header" href="#handling-the-complexities-of-strings">Handling the Complexities of Strings</a></h3>
|
||
<p>To summarize, strings are complicated. Different programming languages make
|
||
different choices about how to present this complexity to the programmer. Rust
|
||
has chosen to make the correct handling of <code>String</code> data the default behavior
|
||
for all Rust programs, which means programmers have to put more thought into
|
||
handling UTF-8 data up front. This trade-off exposes more of the complexity of
|
||
strings than is apparent in other programming languages, but it prevents you
|
||
from having to handle errors involving non-ASCII characters later in your
|
||
development life cycle.</p>
|
||
<p>The good news is that the standard library offers a lot of functionality built
|
||
off the <code>String</code> and <code>&str</code> types to help handle these complex situations
|
||
correctly. Be sure to check out the documentation for useful methods like
|
||
<code>contains</code> for searching in a string and <code>replace</code> for substituting parts of a
|
||
string with another string.</p>
|
||
<p>Let’s switch to something a bit less complex: hash maps!</p>
|
||
</body>
|
||
</html>
|