finally finished slice...
This commit is contained in:
16
notes
16
notes
@ -214,4 +214,20 @@ slices
|
||||
|
||||
reference to a contiguous sequence of elements
|
||||
|
||||
enumerate returns a tuple with counter and reference to thing (counter, &thing)
|
||||
|
||||
slice is a pointer to a string, with a length
|
||||
|
||||
let s = String::from("a a a a");
|
||||
slice = &s[0..2];
|
||||
|
||||
you can drop the first number if it's zero: let slice = &s[..2];
|
||||
or the last number if it's the end of the string: let slice = &s[4..];
|
||||
or both numbers to slice the whole thing: let slice = &s[..];
|
||||
|
||||
you can not create a slice that starts or ends within multibyte unicode parts
|
||||
|
||||
String: a heap allocated vector of bytes that is stored on the heap. It is potentially mutable.
|
||||
&str: an immutable borrowed string slice.
|
||||
|
||||
let s = "string"; // string literal (it's a slice)
|
||||
|
24
plants
Normal file
24
plants
Normal file
@ -0,0 +1,24 @@
|
||||
green shiso
|
||||
green shiso
|
||||
marvel of seasons
|
||||
flower
|
||||
parris island
|
||||
rouge d'hiver
|
||||
rouge d'hiver
|
||||
flower
|
||||
marvel of seasons
|
||||
marvel of seasons
|
||||
rouge d'hiver
|
||||
flower
|
||||
rouge d'hiver
|
||||
parris island
|
||||
black seeded simpson
|
||||
flower
|
||||
chives
|
||||
black seeded simpson
|
||||
dill
|
||||
flower
|
||||
red sails
|
||||
genovese basil
|
||||
deer tongue
|
||||
48 flower
|
@ -1,4 +1,4 @@
|
||||
fn first_word(s: &String) -> usize {
|
||||
fn first_word_int(s: &str) -> usize {
|
||||
let b = s.as_bytes();
|
||||
for (i, &val) in b.iter().enumerate() {
|
||||
if val == b' ' {
|
||||
@ -7,7 +7,23 @@ fn first_word(s: &String) -> usize {
|
||||
}
|
||||
s.len()
|
||||
}
|
||||
fn main() {
|
||||
println!("{}", first_word(&String::from("sadf sdfsd fesf")));
|
||||
|
||||
fn first_word(s: &str) -> &str {
|
||||
let b = s.as_bytes();
|
||||
for (i, &val) in b.iter().enumerate() {
|
||||
if val == b' ' {
|
||||
return &s[..i];
|
||||
}
|
||||
}
|
||||
&s[..]
|
||||
}
|
||||
fn main() {
|
||||
let test_string = "oh my gerd";
|
||||
let string = String::from("sdf sdf esv gs ");
|
||||
let slice = &string[0..first_word_int(&string)];
|
||||
println!("here is the first word: _{}_", slice);
|
||||
|
||||
println!("here is the first word: _{}_", first_word(&string));
|
||||
println!("here is the first word: _{}_", first_word(test_string));
|
||||
println!("{}", test_string);
|
||||
}
|
||||
|
Reference in New Issue
Block a user