mkaz.blog

Working with Rust

Strings

A set of examples working with strings in Rust. There are actually two type of strings in Rust: String and &str. When first starting out this will cause some confusion.

A String type is stored as a vector of valid UTF-8 characters and is growable. While a &str type is a string literal, it is a borrowed slice of a String.

There are a lot of details in there that can confuse you when you start, the best way I found learning is to pay attention to the types functions use, read the compiler messages, and just dive in and play around with them.

let str = "Hi I'm a &str type";
let string = String::from("Hi, I'm a String type");

You can use .to_string() to convert a &str to String

let s = "A string".to_string();

Multi-line Strings

There is no special syntax for multiline strings:

let s = "first line
second line";

This will define s as first line\nsecond line with the new line character.

Use a backslash at end of line, for a multi-line string without the new line character.

let s = "first \
    second";

This will define s as first second.

Raw String Literals

Use raw string literals syntax r#"..."#; to define a string in Rust to avoid escaping special characters.

let s = r#"This has \back\slashes and "quotes" without escaping."#;

Concatenate Strings

String is a growable type, so to concatenate use push to join strings together. Here are two examples, one adding a space char, and then joining a string.

let mut str = String::from("Hola");
str.push(' ');
str.push_str("Mundo");

The &str type supports concatenating strings in Rust using the + operator:

let mut str = "Hola".to_string();
str: str + " mundo";

📌 Note: The use of mut when defining the type makes the variable mutable, this is required to change the variable after initialization, otherwise it is a constant.

Common String Methods

See the std::string::String documentation for a complete list of methods available. Here are a few common ones:

Create Empty String

let s = String::new();

Length of String

let str = "abcdefghijklmnopqrstuvwxyz";
let size = str.len();

Check for Empty String

let s = String::new();
s.is_empty(); // true
 
s.push('t');
s.is_empty(); // false

String to Array of Characters

Technically a string is already a vector, but of bytes and not characters, because UTF-8 bytes and characters are not 1:1. Use .chars() method to return an iterator.

let str = "abcdefghijklmnopqrstuvwxyz";
 
for ch in str.chars() {
    println!("{}", ch);
}

As mentioned, the .chars() method returns an iterator, and not a vector on its own. Notice, when trying to get the length:

let str = "abcdefghijklmnopqrstuvwxyz";
let chars = str.chars();
println!("{}", str.len()); // 26
println!("{}", chars.len()); // error!

To get a vector of characters, use .collect() which collects everything in an iterator and returns a vector.

let str = "abcdefghijklmnopqrstuvwxyz";
let chars:Vec<char> = str.chars().collect();
println!("{}", chars.len());

Split Strings

 
let str = "A beginning is a delicate time";
let v: Vec<&str> = str.split(" ").collect();
 
println!("{:?}", v);

Trim Whitespace

Use .trim() to trim whitespace.

let str = "  Hola mundo  ";
str.trim(); // "Hola mundo"

String Prefix/Suffix

Use .starts_with() and .ends_with() to test starting/ending with a specific string;

let str = "Without change something sleeps inside us";
str.starts_with("Without"); // true
str.ends_with("us");        // true

Use .strip_prefix() and .strip_suffix() to remove a prefix or suffix.

let mut str = "<b>Bold text</b>";
str = str.strip_prefix("<b>").unwrap();
str = str.strip_suffix("</b>").unwrap();
println!("{}", str);\

String Replace

Use .replace() to replace a string.

let s1 = "A wall against the wind.";
let s2 = s1.replace("wall", "feather").replace("against", "in");
println!("{}", s2);
// A feather in the wind

Additional functions

Here are a few more useful methods, see the String documentation for complete list.

  • .contains(Pattern)
  • to_lowercase()
  • to_uppercase()