For characters, you can use s.chars().skip(pos).take(len):

fn main() {
    let s = "Hello, world!";
    let ss: String = s.chars().skip(7).take(5).collect();
    println!("{}", ss);
}

Beware of the definition of Unicode characters though.

For bytes, you can use the slice syntax:

fn main() {
    let s = b"Hello, world!";
    let ss = &s[7..12];
    println!("{:?}", ss);
}
Answer from WiSaGaN on Stack Overflow
🌐
Rust Programming Language
users.rust-lang.org › help
How to get a substring of a String - help - The Rust Programming Language Forum
May 14, 2015 - Hi, what is the best way to get a substring of a String? I couldn't find a substr method or similar. Let's assume I have a String like "Golden Eagle" and I want to get the first 6 characters, that is "Golden". How ca…
Top answer
1 of 2
4

You can use char_indices() then slice the string according to the positions the iterator gives you:

let mut iter = s.char_indices();
let (start, _) = iter.nth(10).unwrap();
let (end, _) = iter.nth(5).unwrap();
let slice = &s[start..end];

However, note that as mentioned in the documentation of chars():

It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead.

2 of 2
2

@ChayimFriedman's answer is of course correct, I just wanted to contribute a more telling example:

fn print_string(s: &str) {
    println!("String: {}", s);
}

fn main() {
    let s: String = "".to_string();

    let mut iter = s.char_indices();

    // Retrieve the position of the char at pos 1
    let (start, _) = iter.nth(1).unwrap();

    // Now the next char will be at position `2`. Which would be
    // equivalent of querying `.next()` or `.nth(0)`.
    // So if we query for `nth(2)` we query 3 characters; meaning
    // the position of character 4.
    let (end, _) = iter.nth(2).unwrap();

    // Gives you a &str, which is exactly what you want.
    // A reference to a substring, zero allocations, zero overhead.
    let substring = &s[start..end];

    print_string(&s);
    print_string(substring);
}
String: 
String: 

I've done it with smileys because smileys are definitely multi-byte unicode characters.

As @ChayimFriedman already noted, the reason why we have to iterate through the char_indices is because unicode characters are variably sized. They can be anywhere from 1 to 8 bytes long, so the only way to find out where the character boundaries are is to actually read the string up to the character we desire.

🌐
Rust Programming Language
users.rust-lang.org › t › rust-substring-function › 24854
Rust substring function? - The Rust Programming Language Forum
February 1, 2019 - I am aware of String in std::string - Rust I can not find a function 'substring' where it takes two args, start (inclusive) nd end (exclusive), and returns a &str pointing to the cahrs in between. Does this strin…
🌐
Dot Net Perls
dotnetperls.com › substring-rust
Rust - Substring Examples - Dot Net Perls
fn main() { let value = "bird"; // Version 1: use slice syntax to take substring. let result1 = &value[1..3]; println!("SUBSTRING: {}", result1); // Version 2: use get() to take substring. let result2 = value.get(1..3).unwrap(); println!("SUBSTRING: {}", result2); } ... We can omit the first ...
🌐
Rust
docs.rs › substring
substring - Rust
use substring::Substring; // Works ... "oobar"); As Rust strings are UTF-8 encoded, the algorithm for finding a character substring is O(n), where n is the byte length of the string....
🌐
DEV Community
dev.to › alexmercedcoder › in-depth-guide-to-working-with-strings-in-rust-1522
In-Depth Guide to Working with Strings in Rust - DEV Community
September 14, 2024 - To replace parts of a string, Rust provides the replace() and replacen() methods. These functions allow you to substitute a substring with a new one, either globally or for a limited number of occurrences.
Find elsewhere
🌐
crates.io
crates.io › crates › substring
substring - crates.io: Rust Package Registry
For full functionality of this site it is necessary to enable JavaScript
🌐
CodeSignal
codesignal.com › learn › courses › string-manipulation-in-rust › lessons › advanced-string-methods-in-rust
Advanced String Methods in Rust
The .find() method in Rust returns an Option<usize>, and it can yield two types of values: ... This variant signifies that the substring was found within the string.
🌐
Rust
doc.rust-lang.org › std › string › struct.String.html
String in std::string - Rust
Returns an iterator over substrings of the given string slice, separated by characters matched by a pattern and yielded in reverse order.
🌐
Rust
docs.rs › substring › latest › substring › trait.Substring.html
Substring in substring - Rust
pub trait Substring { // Required method fn substring(&self, start_index: usize, end_index: usize) -> &str; }
🌐
Programming Idioms
programming-idioms.org › idiom › 62 › find-substring-position › 498 › rust
Find substring position, in Rust
Rust · let i = x.find(y); C · int i=(int)(x-strstr(x,y)); C++ int i = x.find(y); C# var i = x.IndexOf(y); D · auto i = x.countUntil(y); Dart · var i = x.indexOf(y); Elixir · defmodule Dry do def indexOf(x, y, default \\ -1) do case String.split(x, y, parts: 2) do [head, _] -> String.length(head) [_] -> default end end end ·
🌐
GitHub
github.com › Anders429 › substring
GitHub - Anders429/substring: A substring method for string types.
use substring::Substring; ... As Rust strings are UTF-8 encoded, the algorithm for finding a character substring has temporal complexity O(n), where n is the byte length of the string....
Author   Anders429
🌐
GitHub
github.com › bluss › twoway
GitHub - bluss/twoway: Twoway / Fast substring search for strings and byte strings (Rust) / Also assorted benchmarks and string search snippets
Fast substring search for strings and byte strings, using the two-way algorithm. This is the same code as is included in Rust's libstd to “power” str::find(&str), but here it is exposed with some improvements:
Starred by 64 users
Forked by 5 users
Languages   Rust 99.5% | Shell 0.5%
🌐
Educative
educative.io › answers › how-to-check-if-a-string-contains-a-particular-match-in-rust
How to check if a string contains a particular match in Rust
We can use the contains() method of Rust to check if a string contains a particular match or sub-string. It takes only one parameter, which is the sub-string or matches it wants to check.
🌐
Rust
docs.rs › arcstr › latest › arcstr › struct.Substr.html
Substr in arcstr - Rust
Conceptually this is (ArcStr, Range<usize>) with ergonomic helpers. In implementation, the only difference between it and that is that the index type is u32 unless the substr-usize-indices feature is enabled, which makes them use usize.
🌐
Reddit
reddit.com › r/rust › returning a substring of a static str
r/rust on Reddit: Returning a substring of a static str
January 31, 2022 -

I've spent the last three hours trawling the net and stackoverflow. I'm trying to achieve the following,

static mystring: &'static str = "Hello World";

fn substr(start: usize, end: usize) -> str {
    mystring[start..end]
}

fn main() {
    println!("{}", substr(1, 3));
}

However, I get multiple occurrences of error[E0277]: the size for values of typestrcannot be known at compilation time

Can someone help please?

🌐
Rust
docs.rs › common_substrings › latest › common_substrings › struct.Substring.html
Substring in common_substrings - Rust
common_substrings · Source · pub struct Substring { pub sources: HashSet<usize>, pub name: String, pub weight: usize, } Expand description · The result common substring · §sources: HashSet<usize> sources indicates where it comes from §name: String · the name of the substring §weight: usize ·