Rust handles text mainly with the growable, owned String type and the borrowed string slice &str. Their methods let you create, append, search, split, and transform text; the key to using them well is understanding ownership and UTF-8, because Rust strings are not indexed like character arrays.
What “string functions” means in Rust
Rust programmers often say “string functions” when they mean methods for working with strings. In Rust, many commonly used operations are methods on str, and String can use them through deref coercion. For example, you can call contains on a String even though that method is defined for string slices.
A method is called with dot syntax, such as text.trim(). A function is called by its name, such as String::from("hello") or the formatting macro format!. Rust’s standard library provides these tools; there is no single special “string functions” command.
Knowing which type an operation returns is useful. Some methods borrow the original text and return a slice, some create a new owned String, and methods that change text in place generally require a mutable String. Those distinctions follow Rust’s ownership rules rather than being incidental details.
String and str: the two core text types
String is an owned, growable string stored as UTF-8 data. It is useful when text must be built or changed, for example while assembling a message or reading input. A &str is a borrowed view of UTF-8 text. String literals such as "hello" have the type &'static str, and functions often accept &str so they can work with either literals or borrowed parts of a String.
For example, String::from("hello") allocates an owned string, while let view: &str = &owned; borrows its contents. The borrow does not copy the text. As long as the borrow is in use, Rust prevents changes that could invalidate it. This is one reason many APIs take &str as input and return a new String only when they need to produce owned text.
Common ways to make or inspect a string include:
String::new()creates an empty owned string.String::from("text")creates an owned string from a string slice.String::with_capacity(n)creates an empty string with room reserved for at least approximatelynbytes.is_empty()checks whether a string has no bytes, andlen()reports its length in bytes.as_str()borrows aStringas a&str.
Creating and appending text
Use let mut when you need to change an owned string. The push method appends one char, while push_str appends a borrowed string slice. Both update the existing allocation when possible; the string may need to allocate more memory as it grows.
let mut message = String::from("Rust");
message.push('!');
message.push_str(" Strings are UTF-8.");
After these statements, message contains Rust! Strings are UTF-8.. The character passed to push uses single quotes because it is a Rust char; the text passed to push_str is a string slice in double quotes.
When the goal is to combine values into a fresh result, format! is often convenient. It returns a String and leaves the inputs available for later use when they are borrowed for formatting. For example, with let name = "Mira";, let greeting = format!("Hello, {name}!"); produces Hello, Mira!. Rust also supports concatenation with +, but that operator takes ownership of its left-hand String and borrows the right-hand text, so format! can be clearer when combining several pieces.
If you know roughly how much text you will append, String::with_capacity or reserve can reduce repeated reallocations. Capacity is measured in bytes, not characters. Reserving space is an optimization, not a requirement, and ordinary appending is usually the simplest choice unless allocation behavior matters for the task.
Checking, searching, and comparing
String slices provide several methods for answering questions about text. contains checks whether a substring or character pattern occurs. starts_with and ends_with check boundaries, and find returns the byte position of the first match as an Option<usize>. Because the result is optional, code should handle the case where no match exists.
let text = "Rust makes string handling explicit";
let has_rust = text.contains("Rust");
let position = text.find("string");
let begins_with_rust = text.starts_with("Rust");
Here, has_rust and begins_with_rust are booleans, while position is Some(index) if the substring is present and None otherwise. The index is a byte offset, not a count of visible characters. Comparisons using == compare string contents, and Rust’s ordinary string comparison is case-sensitive.
For case-insensitive comparisons, there is no universal built-in rule that works for every language and every user expectation. A simple ASCII-only case-insensitive comparison can use eq_ignore_ascii_case. Unicode case conversion methods are available, but case conversion is not the same thing as full Unicode-aware linguistic comparison or normalization. If text matching has language-specific requirements, choose a library and policy appropriate to that application.
Changing and trimming strings
Methods such as trim, trim_start, and trim_end return borrowed slices with whitespace removed from the relevant edges; they do not modify the original string. For instance, let clean = input.trim(); leaves input unchanged and makes clean refer to the trimmed portion. The returned value is a &str, so call to_owned() or to_string() if an owned result is needed.
replace returns a new owned string with matches substituted, while replacen limits the number of replacements. A compact example is let result = "red,red,blue".replacen("red", "green", 1);, which produces green,red,blue. These methods do not change the original slice. For in-place editing, methods on a mutable String, such as push_str, are appropriate; some editing methods require the insertion or removal position to be a valid UTF-8 character boundary.
Whitespace behavior deserves attention when cleaning input. trim removes leading and trailing Unicode whitespace, not punctuation and not whitespace inside the string. Thus trimming " hello world " yields "hello world", while the space between the words remains. If an application should remove only a specific set of characters, inspect the relevant pattern-based methods rather than assuming trim removes arbitrary symbols.
Splitting text into parts
split returns an iterator over pieces separated by a pattern. split_whitespace separates on runs of whitespace, and lines iterates over lines. These methods generally yield borrowed &str slices, which avoids allocating a new string for every piece. Collect into a Vec only when you need to store the pieces or use them more than once.
let sentence = "Rust is fast";
let words: Vec<&str> = sentence.split_whitespace().collect();
let fields: Vec<&str> = "one,two,three".split(',').collect();
The first vector contains Rust, is, and fast; the second contains three fields. A comma split is suitable for a simple delimited example, but it is not a complete CSV parser: real CSV can include quoted fields, commas inside quotes, and escaped quotation marks. Use a CSV library when those rules matter.
Rust also offers methods such as split_once, which returns the first pair of pieces around a matching separator when one is found. Use it when a string has a single delimiter of interest, such as a simple key-value line. As with other string operations, splitting does not automatically validate that the input has the structure your program expects; check for missing pieces and malformed data.
UTF-8, length, and indexing
A Rust String stores valid UTF-8, and its len() method returns the number of bytes. It does not return the number of Unicode scalar values or the number of user-perceived characters. For example, the character é encoded as the single Unicode scalar U+00E9 occupies two bytes in UTF-8, so String::from("é").len() is 2, while iterating with chars() produces one scalar value.
Direct indexing such as text[0] is not supported for Rust strings. A byte index might fall in the middle of a multi-byte UTF-8 sequence, so the operation would not have a consistent character meaning. Use chars() to iterate over Unicode scalar values, bytes() when byte-level processing is intended, or char_indices() when you need each scalar value along with its byte offset.
Even chars() does not necessarily count what a person sees as one character. A visible symbol may be represented by multiple Unicode scalar values, as with some accented text or emoji sequences. Grapheme-cluster handling requires Unicode segmentation rules, typically through an appropriate crate. When slicing by byte range, ensure both endpoints are UTF-8 character boundaries; get(range) is a safe option because it returns None rather than panicking for an invalid range.
Ownership, conversions, and practical choices
Choose &str for a function parameter when the function only needs to read text. This accepts both string literals and borrowed String values without forcing the caller to transfer ownership. Choose String for a return value when the function creates new text that must outlive its inputs, or when the caller needs an owned, mutable result.
Conversions make the ownership change explicit. to_string() and to_owned() can create an owned string from borrowed text. as_str() borrows from a String. The into_bytes() method consumes a String and returns its UTF-8 bytes as a vector. Conversely, String::from_utf8(bytes) attempts to build a string from bytes and returns a Result, because arbitrary bytes may not be valid UTF-8. Handle that result rather than assuming every byte sequence is text.
A practical rule of thumb is:
- Use
&strto inspect text without taking ownership. - Use
Stringwhen you need to own or grow text. - Use
chars()for scalar-value iteration andbytes()for encoded bytes. - Use a parsing library for structured formats such as CSV, JSON, or URLs instead of relying on a quick split.
Frequently Asked Questions
How do I convert a &str to a String?
Call to_string() or to_owned() on the slice, or use String::from(slice). Each creates an owned string containing the text. For example, let owned = String::from("hello"); creates a String from a string literal.
How do I get the first character of a Rust string?
Use text.chars().next(). It returns an Option<char>, so an empty string produces None. Avoid indexing at zero: Rust strings do not support character indexing, and the first character may occupy more than one byte.
Why does String::len return a surprising number?
len() counts UTF-8 bytes. For ASCII text, bytes and characters happen to have the same count, but non-ASCII text can use multiple bytes per scalar value. Use chars().count() to count Unicode scalar values, bearing in mind that this still may differ from the number of visible graphemes.
Does trim modify the original String?
No. trim() returns a borrowed slice without leading or trailing whitespace, leaving the original string unchanged. Assign that slice back only if the ownership and borrowing rules allow it, or create a new owned value with to_owned() when necessary.
How can I change a String in place?
Declare it mutable, then use methods such as push to append a character or push_str to append text. Many transformation methods, including replace, instead return a new string. Check each method’s return type and ownership behavior to know whether it edits the original or produces a result.
Related
- Graphing the Line y = -1: Points, Slope, and Examples
- How to Split Data in Google Sheets
- SOLIDWORKS Split Part: Create Two Separate Bodies Guide
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- ISERROR with VLOOKUP: How to Handle Lookup ErrorsYes. In Excel, ISERROR can test a VLOOKUP result and report whether it returns an error; wrap the…
- Excel FORECAST vs TREND: Which Function to Use?In Excel, FORECAST.LINEAR predicts one value from a linear relationship, while TREND calculates one or more values from…
- Excel Filter Including Wrong Data? Find the CauseIf an Excel filter includes the wrong data, first check that the filter covers the correct range and…
- Excel Formula for Fiscal Year: Step-by-Step GuideThe simplest Excel formula for determining a fiscal year is =YEAR(A2)+(MONTH(A2)>=FiscalStartMonth), where A2 contains the date and FiscalStartMonth…
- Excel Slicer Custom Sort: Control the Order of ItemsTo custom-sort an Excel slicer, create or use an Excel custom list for the item labels, then open…
- SQL SPLIT_PART Function: Syntax, Examples, and AlternativesSPLIT_PART is a SQL function that returns one part of a string separated by a chosen delimiter. In…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.