Type ::std::string::String

Overview

Methods

fn from(value: String) -> String

Constructs a string from another string.

Examples

Basic usage:

let s = String::from("hello");
assert_eq!(s, "hello");
fn from_str(value: String) -> String
Deprecated:Use String::from instead
fn new() -> String

Creates a new empty String.

Given that the String is empty, this will not allocate any initial buffer. While that means that this initial operation is very inexpensive, it may cause excessive allocation later when you add data. If you have an idea of how much data the String will hold, consider the with_capacity method to prevent excessive re-allocation.

Examples

Basic usage:

let s = String::new();
fn with_capacity(capacity: i64) -> String

Creates a new empty String with at least the specified capacity.

Strings have an internal buffer to hold their data. The capacity is the length of that buffer, and can be queried with the capacity method. This method creates an empty String, but one with an initial buffer that can hold at least capacity bytes. This is useful when you may be appending a bunch of data to the String, reducing the number of reallocations it needs to do.

If the given capacity is 0, no allocation will occur, and this method is identical to the new method.

Examples

Basic usage:

let s = String::with_capacity(10);

// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);

// These are all done without reallocating...
let cap = s.capacity();

for _ in 0..10 {
   s.push('a');
}

assert_eq!(s.capacity(), cap);

// ...but this may make the string reallocate
s.push('a');
fn cmp(self, rhs: String) -> Ordering
fn len(self) -> i64

Returns the length of self.

This length is in bytes, not chars or graphemes. In other words, it might not be what a human considers the length of the string.

Examples

Basic usage:

let len = "foo".len();
assert_eq!(3, len);

assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
fn starts_with(self, other: String) -> bool

Returns true if the given pattern matches a prefix of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Examples

Basic usage:

let bananas = "bananas";

assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
fn ends_with(self, other: String) -> bool

Returns true if the given pattern matches a suffix of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Examples

Basic usage:

let bananas = "bananas";

assert!(bananas.ends_with("anas"));
assert!(!bananas.ends_with("nana"));
fn capacity(self) -> i64

Returns this String's capacity, in bytes.

Examples

Basic usage:

let s = String::with_capacity(10);

assert!(s.capacity() >= 10);
fn clear(self) -> Tuple

Truncates this String, removing all contents.

While this means the String will have a length of zero, it does not touch its capacity.

Examples

Basic usage:

let s = "foo";

s.clear();

assert!(s.is_empty());
assert_eq!(0, s.len());
assert_eq!(3, s.capacity());
fn contains(self, other: String) -> bool

Returns true if the given pattern matches a sub-slice of this string slice.

Returns false if it does not.

The pattern can be a String, char, or a function or closure that determines if a character matches.

Examples

Basic usage:

let bananas = "bananas";

assert!(bananas.contains("nana"));
assert!(!bananas.contains("apples"));
fn push(self, c: char) -> Tuple

Appends the given [char] to the end of this String.

Examples

Basic usage:

let s = "abc";

s.push('1');
s.push('2');
s.push('3');

assert_eq!("abc123", s);
fn push_str(self, other: String) -> Tuple

Appends a given string slice onto the end of this String.

Examples

Basic usage:

let s = "foo";

s.push_str("bar");

assert_eq!("foobar", s);
fn reserve(self, additional: i64) -> Tuple

Reserves capacity for at least additional bytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if capacity is already sufficient.

Panics

Panics if the new capacity overflows [usize].

Examples

Basic usage:

let s = String::new();

s.reserve(10);

assert!(s.capacity() >= 10);

This might not actually increase the capacity:

let s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
fn reserve_exact(self, additional: i64) -> Tuple

Reserves the minimum capacity for at least additional bytes more than the current length. Unlike reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling reserve_exact, capacity will be greater than or equal to self.len() + additional. Does nothing if the capacity is already sufficient.

Panics

Panics if the new capacity overflows [usize].

Examples

Basic usage:

let s = String::new();

s.reserve_exact(10);

assert!(s.capacity() >= 10);

This might not actually increase the capacity:

let s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve_exact(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
fn from_utf8(bytes: Bytes) -> Result

Converts a vector of bytes to a String.

A string ([String]) is made of bytes ([u8]), and a vector of bytes (Vec<u8>) is made of bytes, so this function converts between the two. Not all byte slices are valid Strings, however: String requires that it is valid UTF-8. from_utf8() checks to ensure that the bytes are valid UTF-8, and then does the conversion.

If you are sure that the byte slice is valid UTF-8, and you don't want to incur the overhead of the validity check, there is an unsafe version of this function, from_utf8_unchecked, which has the same behavior but skips the check.

The inverse of this method is into_bytes.

Errors

Returns [Err] if the slice is not UTF-8 with a description as to why the provided bytes are not UTF-8. The vector you moved in is also included.

Examples

Basic usage:

// some bytes, in a vector
let sparkle_heart = Bytes::from_vec([240u8, 159u8, 146u8, 150u8]);

// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();

assert_eq!("💖", sparkle_heart);

Incorrect bytes:

// some invalid bytes, in a vector
let sparkle_heart = Bytes::from_vec([0u8, 159u8, 146u8, 150u8]);

assert!(String::from_utf8(sparkle_heart).is_err());

See the docs for [FromUtf8Error] for more details on what you can do with this error.

Returns a byte slice of this String's contents.

The inverse of this method is from_utf8.

Examples

Basic usage:

let s = "hello";

assert_eq!(b"hello", s.as_bytes());
assert!(is_readable(s));

Returns a byte slice of this String's contents while moving the string.

The inverse of this method is from_utf8.

Examples

Basic usage:

let s = "hello";

assert_eq!(b"hello", s.into_bytes());
assert!(!is_readable(s));
fn clone(self) -> String

Clones the string and its underlying storage.

Examples

Basic usage:

let a = "h";
let b = a;
b.push('i');

// `a` and `b` refer to the same underlying string.
assert_eq!(a, b);

let c = b.clone();
c.push('!');
assert_ne!(a, c);

Shrinks the capacity of this String to match its length.

Examples

Basic usage:

let s = "foo";

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to_fit();
assert_eq!(3, s.capacity());
fn char_at(self, index: i64) -> Option

Access the character at the given byte index.

Returns None if the index is out of bounds or not a character boundary.

Examples

let s = "おはよう";
assert_eq!(s.char_at(0), Some(''));
assert_eq!(s.char_at(1), None);
assert_eq!(s.char_at(2), None);
assert_eq!(s.char_at(3), Some(''));
fn split(self, value) -> Iterator

An iterator over substrings of this string slice, separated by characters matched by a pattern.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Iterator behavior

The returned iterator will be a [DoubleEndedIterator] if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rsplit method can be used.

Examples

Simple patterns:

let v = "Mary had a little lamb".split(' ').collect::<Vec>();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

let v = "".split('X').collect::<Vec>();
assert_eq!(v, [""]);

let v = "lionXXtigerXleopard".split('X').collect::<Vec>();
assert_eq!(v, ["lion", "", "tiger", "leopard"]);

let v = "lion::tiger::leopard".split("::").collect::<Vec>();
assert_eq!(v, ["lion", "tiger", "leopard"]);

let v = "abc1def2ghi".split(char::is_numeric).collect::<Vec>();
assert_eq!(v, ["abc", "def", "ghi"]);

let v = "lionXtigerXleopard".split(char::is_uppercase).collect::<Vec>();
assert_eq!(v, ["lion", "tiger", "leopard"]);

A more complex pattern, using a closure:

let v = "abc1defXghi".split(|c| c == '1' || c == 'X').collect::<Vec>();
assert_eq!(v, ["abc", "def", "ghi"]);

If a string contains multiple contiguous separators, you will end up with empty strings in the output:

let x = "||||a||b|c";
let d = x.split('|').collect::<Vec>();

assert_eq!(d, ["", "", "", "", "a", "", "b", "c"]);

Contiguous separators are separated by the empty string.

let x = "(///)";
let d = x.split('/').collect::<Vec>();

assert_eq!(d, ["(", "", "", ")"]);

Separators at the start or end of a string are neighbored by empty strings.

let d = "010".split("0").collect::<Vec>();
assert_eq!(d, ["", "1", ""]);

When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.

let f = "rust".split("").collect::<Vec>();
assert_eq!(f, ["", "r", "u", "s", "t", ""]);

Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:

let x = "    a  b c";
let d = x.split(' ').collect::<Vec>();

assert_eq!(d, ["", "", "", "", "a", "", "b", "c"]);

It does not give you:

assert_eq!(d, ["a", "b", "c"]);

Use split_whitespace for this behavior.

fn split_str(self, value) -> Iterator
Deprecated:Use String::split instead
fn trim(self) -> String

Returns a string slice with leading and trailing whitespace removed.

'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

Examples

Basic usage:

let s = "\n Hello\tworld\t\n";

assert_eq!("Hello\tworld", s.trim());

Returns a string slice with trailing whitespace removed.

'Whitespace' is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

Text directionality

A string is a sequence of bytes. end in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

Examples

Basic usage:

let s = "\n Hello\tworld\t\n";
assert_eq!("\n Hello\tworld", s.trim_end());

Directionality:

let s = "  English  ";
assert!(Some('h') == s.trim_end().chars().rev().next());

let s = "  עברית  ";
assert!(Some('ת') == s.trim_end().chars().rev().next());
fn replace(self, from: String, to: String) -> String

Replaces all matches of a pattern with another string.

replace creates a new [String], and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice.

Examples

Basic usage:

let s = "this is old";

assert_eq!("this is new", s.replace("old", "new"));
assert_eq!("than an old", s.replace("is", "an"));

When the pattern doesn't match, it returns this string slice as [String]:

let s = "this is old";
assert_eq!(s, s.replace("cookie monster", "little lamb"));
fn is_empty(self) -> bool

Returns true if self has a length of zero bytes.

Examples

Basic usage:

let s = "";
assert!(s.is_empty());

let s = "not empty";
assert!(!s.is_empty());

Returns an iterator over the chars of a string slice.

As a string slice consists of valid UTF-8, we can iterate through a string slice by char. This method returns such an iterator.

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.

Examples

Basic usage:

let word = "goodbye";

let count = word.chars().count();
assert_eq!(7, count);

let chars = word.chars();

assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());

assert_eq!(None, chars.next());

Remember, chars might not match your intuition about characters:

let y = "";

let chars = y.chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());
fn get(self, key) -> Option

Returns a subslice of str.

This is the non-panicking alternative to indexing the str. Returns [None] whenever equivalent indexing operation would panic.

Examples

let v = "🗻∈🌏";

assert_eq!(Some("🗻"), v.get(0..4));

// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());

// out of bounds
assert!(v.get(..42).is_none());
fn parse<i64>(self) -> Result

Parses this string into an integer.

Errors

Will return [Err] if it's not possible to parse this string slice into an integer.

Examples

Basic usage

let four = "4".parse::<i64>()?;
assert_eq!(4, four);
fn parse<char>(self) -> Result

Parses this string into a character.

Errors

Will return [Err] if it's not possible to parse this string slice into an integer.

Examples

Basic usage

let a = "a".parse::<char>()?;
assert_eq!('a', a);

Protocols

protocol add
let output = value + b

The add operation for strings.

protocol add_assign
value += b

The add assign operation for strings.

protocol index_get
let output = value[index]

Get a specific string index.