Add string slicing example
This commit is contained in:
parent
30649df52e
commit
6c3d7f50ce
2 changed files with 27 additions and 0 deletions
9
string_slicing/Cargo.toml
Normal file
9
string_slicing/Cargo.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "string_slicing"
|
||||
version = "0.1.0"
|
||||
authors = ["laurens <miers132@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
18
string_slicing/src/main.rs
Normal file
18
string_slicing/src/main.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
fn first_word(s: &String) -> &str {
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
for (i, &item) in bytes.iter().enumerate() {
|
||||
if item == b' ' {
|
||||
return &s[..i]
|
||||
}
|
||||
}
|
||||
|
||||
&s[..]
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let s = String::from("Hello world");
|
||||
|
||||
println!("String: {}", s);
|
||||
println!("First word: {}", first_word(&s));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue