Skip to content

Commit 7c046fe

Browse files
committed
slice 遇到空格 返回空格之前的单词
1 parent 8d52a62 commit 7c046fe

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+41
-1
lines changed

rust-by-example/common/src/main.rs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,37 @@ fn main() {
136136

137137
s.clear(); // 清空了字符串,使其等于 ""
138138

139-
print!("The word value: {}", word);
139+
println!("The word value: {}", word);
140140

141141

142+
let s = String::from("hello world");
143+
144+
let slice = &s[0..2];
145+
let slice = &s[..2];
146+
let len = s.len();
147+
148+
let slice = &s[3..len];
149+
let slice = &s[3..];
150+
let slice = &s[0..len];
151+
let slice = &s[..];
152+
let hello = &s[0..=4];
153+
let world = &s[6..=10];
154+
155+
let my_string = String::from("hello world");
156+
157+
// first_word_good 中传入 `String` 的 slice
158+
let word = first_word_good(&my_string[..]);
159+
160+
let my_string_literal = "hello world";
161+
162+
// first_word_good 中传入字符串字面值的 slice
163+
let word = first_word_good(&my_string_literal[..]);
164+
165+
// 因为字符串字面值 **就是** 字符串 slice,
166+
// 这样写也可以,即不使用 slice 语法!
167+
let word = first_word_good(my_string_literal);
168+
169+
println!("Now the word value: {}", word);
142170
}
143171

144172
fn first_word(s: &String) -> usize {
@@ -153,6 +181,18 @@ fn first_word(s: &String) -> usize {
153181
s.len()
154182
}
155183

184+
fn first_word_good(s: &str) -> &str {
185+
let bytes = s.as_bytes();
186+
187+
for (i, &item) in bytes.iter().enumerate() {
188+
if item == b' ' {
189+
return &s[0..i]
190+
}
191+
}
192+
193+
&s[..]
194+
}
195+
156196
fn change_mut(s: &mut String) {
157197
s.push_str(", world");
158198
}
30.3 KB
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)