File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -121,6 +121,62 @@ fn compare(string: String) {
121121Converting a ` String ` to a ` &str ` is cheap, but converting the ` &str ` to a
122122` String ` involves an allocation.
123123
124+ ## Indexing strings
125+
126+ You may be tempted to try to access a certain character of a ` String ` , like
127+ this:
128+
129+ ``` {rust,ignore}
130+ let s = "hello".to_string();
131+
132+ println!("{}", s[0]);
133+ ```
134+
135+ This does not compile. This is on purpose. In the world of UTF-8, direct
136+ indexing is basically never what you want to do. The reason is that each
137+ charater can be a variable number of bytes. This means that you have to iterate
138+ through the characters anyway, which is a O(n) operation.
139+
140+ To iterate over a string, use the ` graphemes() ` method on ` &str ` :
141+
142+ ``` {rust}
143+ let s = "αἰθήρ";
144+
145+ for l in s.graphemes(true) {
146+ println!("{}", l);
147+ }
148+ ```
149+
150+ This will print out each character in turn, as you'd expect: first "α", then
151+ "ἰ", etc. You can see that this is different than just the individual bytes.
152+ Here's a version that prints out each byte:
153+
154+ ``` {rust}
155+ let s = "αἰθήρ";
156+
157+ for l in s.as_bytes().iter() {
158+ println!("{}", l);
159+ }
160+ ```
161+
162+ This will print:
163+
164+ ``` {notrust,ignore}
165+ 206
166+ 177
167+ 225
168+ 188
169+ 176
170+ 206
171+ 184
172+ 206
173+ 174
174+ 207
175+ 129
176+ ```
177+
178+ Many more bytes than graphemes!
179+
124180# Other Documentation
125181
126182* [ the ` &str ` API documentation] ( /std/str/index.html )
You can’t perform that action at this time.
0 commit comments