rustHow do I get a slice from a string in Rust?
You can get a slice from a string in Rust using the slice
method. This method takes two parameters, the start index and the end index of the slice. The following example code will create a slice of the string "Hello World"
from index 1 to index 5:
let s = "Hello World";
let slice = &s[1..5];
println!("{}", slice);
Output example
ello
Code explanation
let s = "Hello World";
: This creates a string variables
with the value"Hello World"
.let slice = &s[1..5];
: This creates a slice of the strings
from index 1 to index 5 and assigns it to the variableslice
.println!("{}", slice);
: This prints the value of the variableslice
to the console.
Helpful links
More of Rust
- How do I print the type of a variable in Rust?
- How to remove an element from a Rust HashMap if a condition is met?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to get a capture group using Rust regex?
- How to extract data with regex in Rust?
- How to escape dots with regex in Rust?
See more codes...