String Functions in Rust

The standard library’s str module and String type provide many useful string-related functions. Here are some examples to give you a sense of the available operations.

fn main() {
    // We alias println! to a shorter name as we'll use it a lot below.
    macro_rules! p {
        ($($arg:tt)*) => {
            println!($($arg)*);
        };
    }

    // Here's a sample of the functions available for strings.
    // Note that in Rust, some operations are methods on String or &str,
    // while others are functions in the str module.

    p!("Contains:  {}", "test".contains("es"));
    p!("Count:     {}", "test".matches("t").count());
    p!("HasPrefix: {}", "test".starts_with("te"));
    p!("HasSuffix: {}", "test".ends_with("st"));
    p!("Index:     {}", "test".find("e").unwrap_or(std::usize::MAX));
    p!("Join:      {}", ["a", "b"].join("-"));
    p!("Repeat:    {}", "a".repeat(5));
    p!("Replace:   {}", "foo".replace("o", "0"));
    p!("Replace:   {}", "foo".replacen("o", "0", 1));
    p!("Split:     {:?}", "a-b-c-d-e".split("-").collect::<Vec<&str>>());
    p!("ToLower:   {}", "TEST".to_lowercase());
    p!("ToUpper:   {}", "test".to_uppercase());
}

When you run this program, you’ll see:

$ cargo run
Contains:  true
Count:     2
HasPrefix: true
HasSuffix: true
Index:     1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     ["a", "b", "c", "d", "e"]
ToLower:   test
ToUpper:   TEST

In Rust, string manipulation is often done through methods on String or &str types, rather than functions in a separate module. However, the str module does provide some additional string-related utilities.

Some key differences to note:

  1. Rust uses String for owned strings and &str for string slices.
  2. Many operations in Rust are methods rather than standalone functions.
  3. Rust’s split returns an iterator, which we collect into a Vec for printing.
  4. Rust’s find returns an Option<usize>, which we handle with unwrap_or.
  5. Rust doesn’t have a direct equivalent to Go’s strings.Count, so we use matches().count().

You can find more string-related functions and methods in the Rust documentation for the str module and String type.