Strings

51 articles
Error: "expected &str, found String" — How to Fix Fix the 'expected &str, found String' error by converting the String to a slice with .as_str() or passing a reference with &. How to Check if a String Contains a Substring in Rust Use the `contains()` method on the `&str` type to check for a substring, which returns a boolean. How to check if string contains substring Use the `contains` method on string slices (`&str`) or `String` types, as it returns a boolean indicating whether the substring exists. How to compare strings in Rust Use the standard comparison operators (`==`, `!=`, `<`, `>`) directly on string types, as Rust implements the `PartialEq` and `PartialOrd` traits for `&str`, `String`, and `&String`. How to Compare Strings with Different Encodings in Rust Convert strings to UTF-8 using std::str::from_utf8 or encoding_rs before comparing with the == operator. How to concatenate strings Use `format!` for one-off concatenation or `String::push_str` (or the `+` operator) when building strings in a loop. How to Concatenate Strings in Rust Concatenate strings in Rust using the format! macro or push_str method to join text efficiently. How to Convert a Number to a String in Rust Use the `ToString` trait for simple conversions or `format!` for formatted output, as both are idiomatic and efficient in Rust. How to Convert a String to an Integer in Rust Convert a string to an integer in Rust using the parse method with error handling. How to Convert a String to Uppercase or Lowercase in Rust Use the `to_uppercase()` and `to_lowercase()` methods on string slices (`&str`) or `String` types to convert text, which return a new `String` containing the transformed characters. How to convert between String and str You convert a `String` to a `&str` by borrowing it with `&` or `&s[..]`, while converting a `&str` to a `String` requires allocation using `.to_string()` or `String::from()`. How to Convert Between String and &str in Rust You convert a `String` to `&str` using the `as_str()` method or by simply borrowing it, while converting `&str` to `String` requires calling the `to_string()` method or using `String::from()`. How to Create Strings in Rust You create strings in Rust using either string literals (immutable `&str` slices) for compile-time constants or the `String` type for owned, mutable data. How to Efficiently Build Strings in Rust Use `String::with_capacity()` to pre-allocate memory when you know the approximate final size, or rely on `String`'s internal growth strategy for unknown sizes, as it already doubles capacity efficiently to minimize reallocations. How to format strings Use the `format!` macro for creating new strings in memory and the `println!` or `print!` macros for outputting to the console. How to Format Strings in Rust with format! Use the `format!` macro to construct new `String` values by embedding expressions directly into a template string, similar to C's `printf` but with type safety and no format string vulnerabilities. How to Get a Substring (Slice) from a String in Rust You cannot directly slice a `String` using integer indices because Rust enforces UTF-8 validity, so you must use `char_indices()` to find valid byte boundaries or use the `split_at` method with a pre-calculated byte offset. How to Handle Character Encodings in Rust Rust uses UTF-8 by default for strings, requiring byte-level reading and conversion for other encodings. How to Handle Different Number and Date Formats in Rust Use the chrono crate to parse and format various number and date strings in Rust. How to Handle Right-to-Left Text in Rust Rust natively supports Right-to-Left text via UTF-8 encoding, requiring no special handling for storage or processing. How to Handle Unicode in Rust Rust handles Unicode natively via UTF-8 Strings, allowing safe iteration over characters using the chars() method. How to Handle UTF-8 Strings in Rust Use the `String` type to store and manipulate growable, UTF-8 encoded text in Rust. How to iterate over characters Iterate over characters in a Rust string using the .chars() method to handle UTF-8 encoding correctly. How to Iterate Over Characters in a Rust String You can iterate over the characters of a Rust string using the `.chars()` method, which yields `char` items representing Unicode scalar values, or `.bytes()` for raw byte access. How to Join a Vector of Strings in Rust Use the `join` method on a `&[String]` or `&[&str]` slice, passing the desired separator as an argument. How to Localize a Rust Application (fluent-rs) You localize a Rust application by adding the `fluent-bundle` and `intl-memoizer` crates, loading `.ftl` resource files into a `FluentBundle`, and resolving messages with `FluentArgs`. How to Normalize Unicode Strings in Rust Normalize Unicode strings in Rust by adding the unicode-normalization crate and calling the nfc() method on your string. How to Pad a String in Rust Pad a string in Rust using the format! macro with alignment specifiers like < for left and > for right padding. How to Parse a String with a Custom Delimiter in Rust Use the split method with your custom delimiter to break a string into an iterator of substrings in Rust. How to parse string to number Use the `parse()` method on your string slice, which returns a `Result` that you must handle to avoid panics. How to Read a String Line by Line in Rust Read a string line by line in Rust using the lines() iterator on a BufReader. How to replace substring in Rust Use the replace method on a String to create a new string with the specified substring swapped out. How to Replace Text in a String in Rust Use the replace method on a String to generate a new string with the specified text substituted. How to Reverse a String in Rust You can reverse a string in Rust by converting it to a vector of characters, reversing that vector, and collecting it back into a String, which correctly handles multi-byte Unicode characters. How to split a string Use split_whitespace() to separate words by spaces or split() with a delimiter to break a string at specific characters in Rust. How to Split a String in Rust Split a string in Rust using split_whitespace() for spaces or split() with a custom delimiter to iterate over substrings. How to Trim Whitespace from a String in Rust Remove leading and trailing whitespace from a Rust string using the .trim() method. How to trim whitespace from string Use the built-in `trim()`, `trim_start()`, and `trim_end()` methods on string slices (`&str`) to remove leading, trailing, or both types of whitespace. How to Use ICU Collation in Rust Use the `icu_collator` crate to sort strings according to Unicode Collation Algorithm rules. Add the dependency to your `Cargo.toml` and initialize a collator with your target locale. How to use regex in Rust Use the regex crate with Regex::new() to compile patterns and replace_all() to transform strings in Rust. How to Use String Interpolation in Rust Rust does not support native string interpolation like Python or JavaScript; instead, you use the `format!` macro or the `println!` macro with `{}` placeholders to inject variables into strings. How to Use the unicode-segmentation Crate for Grapheme Clusters Split strings into user-perceived characters using the unicode_segmentation crate's graphemes iterator. How to Work with Non-ASCII Text in Rust Use Rust's built-in UTF-8 String type and the .chars() iterator to safely handle non-ASCII text. How to Work with Raw Strings in Rust (r#""#) Use raw string literals (prefixed with `r`) when you need to include many backslashes or quotes without escaping them, as the content between the delimiters is treated literally. String vs &str in Rust: What Is the Difference? String owns mutable heap text while &str is an immutable borrowed reference to text. What is OsStr and OsString OsStr and OsString are Rust types for handling file paths and arguments that may contain invalid Unicode, preventing panics. What Is OsString and When Should I Use It? Use OsString with std::env::args_os to handle command line arguments containing invalid Unicode without panicking. What is the Cow str type Cow<'a, str> is a Rust enum that efficiently handles both borrowed string slices and owned strings, cloning only when modification is required. What Is the Difference Between chars() and bytes() in Rust? chars() iterates over Unicode characters while as_bytes() iterates over raw UTF-8 bytes. What is the difference between String and str String is an owned, growable UTF-8 text type, while str is an unsized slice type used for immutable references to string data. Why Is String Indexing Not Allowed in Rust? Rust prevents string indexing to ensure UTF-8 safety, requiring iteration or byte slicing instead.