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: u64) -> 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 len(self) -> u64

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) -> u64

Returns this String's capacity, in bytes.

Examples

Basic usage:

let s = String::with_capacity(10);

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

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)

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)

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: u64)

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: u64)

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));

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: u64) -> 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: any) -> any
Deprecated:Use String::split instead

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_once(self, value: any) -> Option

Splits the string on the first occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

Examples

assert_eq!("cfg".split_once('='), None);
assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
fn split_str(value: String, value1: any) -> any
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());
fn chars(self) -> Chars

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: any) -> 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);

Returns the lowercase equivalent of this string slice, as a new [String].

'Lowercase' is defined according to the terms of the Unicode Derived Core Property Lowercase.

Since some characters can expand into multiple characters when changing the case, this function returns a [String] instead of modifying the parameter in-place.

Examples

Basic usage:

let s = "HELLO";

assert_eq!("hello", s.to_lowercase());

A tricky example, with sigma:

let sigma = "Σ";

assert_eq!("σ", sigma.to_lowercase());

// but at the end of a word, it's ς, not σ:
let odysseus = "ὈΔΥΣΣΕΎΣ";

assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());

Languages without case are not changed:

let new_year = "农历新年";

assert_eq!(new_year, new_year.to_lowercase());

Returns the uppercase equivalent of this string slice, as a new [String].

'Uppercase' is defined according to the terms of the Unicode Derived Core Property Uppercase.

Since some characters can expand into multiple characters when changing the case, this function returns a [String] instead of modifying the parameter in-place.

Examples

Basic usage:

let s = "hello";

assert_eq!("HELLO", s.to_uppercase());

Scripts without case are not changed:

let new_year = "农历新年";

assert_eq!(new_year, new_year.to_uppercase());

One character can become multiple:

let s = "tschüß";

assert_eq!("TSCHÜSS", s.to_uppercase());

Trait Implementations

impl Clone for String
fn clone(value: any) -> any

Clone the specified value.

Examples

let a = 42;
let b = a;
let c = a.clone();

a += 1;

assert_eq!(a, 43);
assert_eq!(b, 42);
assert_eq!(c, 42);
impl PartialEq for String
fn eq(value: any, value1: any) -> bool

Compare two values for equality.

Examples

assert_eq!(1.eq(2), false);
assert_eq!(2.eq(2), true);
assert_eq!(2.eq(1), false);
fn ne(value: any, value1: any) -> bool

Compare two values for inequality.

Examples

assert_eq!(1.ne(2), true);
assert_eq!(2.ne(2), false);
assert_eq!(2.ne(1), true);
impl Eq for String
impl PartialOrd for String
fn partial_cmp(value: any, value1: any) -> Option

Compare two values.

Examples

use std::cmp::Ordering;

assert_eq!(1.partial_cmp(2), Some(Ordering::Less));
assert_eq!(2.partial_cmp(2), Some(Ordering::Equal));
assert_eq!(2.partial_cmp(1), Some(Ordering::Greater));
fn lt(value: any, value1: any) -> bool

Tests less than (for self and other) and is used by the < operator.

Examples

assert_eq!(1.0 < 1.0, false);
assert_eq!(1.0 < 2.0, true);
assert_eq!(2.0 < 1.0, false);
fn le(value: any, value1: any) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator.

Examples

assert_eq!(1.0 <= 1.0, true);
assert_eq!(1.0 <= 2.0, true);
assert_eq!(2.0 <= 1.0, false);
fn gt(value: any, value1: any) -> bool

Tests greater than (for self and other) and is used by the > operator.

Examples

assert_eq!(1.0 > 1.0, false);
assert_eq!(1.0 > 2.0, false);
assert_eq!(2.0 > 1.0, true);
fn ge(value: any, value1: any) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator.

Examples

assert_eq!(1.0 >= 1.0, true);
assert_eq!(1.0 >= 2.0, false);
assert_eq!(2.0 >= 1.0, true);
impl Ord for String
fn cmp(value: any, value1: any) -> Ordering

Compare two values.

Examples

use std::cmp::Ordering;

assert_eq!(1.cmp(2), Ordering::Less);
assert_eq!(2.cmp(2), Ordering::Equal);
assert_eq!(2.cmp(1), Ordering::Greater);
fn min(value: any, value1: any) -> Ordering

Return the minimum of two values.

Examples

assert_eq!(1.min(2), 1);
assert_eq!(2.min(2), 2);
assert_eq!(2.min(1), 1);
fn max(value: any, value1: any) -> Ordering

Return the maximum of two values.

Examples

assert_eq!(1.max(2), 2);
assert_eq!(2.max(2), 2);
assert_eq!(2.max(1), 2);

Protocols

protocol ADD
let $out = value + $b

The add operation for strings.

protocol ADD_ASSIGN
value += $b

The add assign operation for strings.

protocol INDEX_GET
let $out = value[index]

Get a specific string index.

protocol CLONE
let $out = clone(value)

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);
protocol PARTIAL_EQ
if value == b { }

Test two strings for partial equality.

Examples

use std::ops::partial_eq;

assert_eq!(partial_eq("a", "a"), true);
assert_eq!(partial_eq("a", "ab"), false);
assert_eq!(partial_eq("ab", "a"), false);
protocol EQ
if value == b { }

Test two strings for total equality.

Examples

use std::ops::eq;

assert_eq!(eq("a", "a"), true);
assert_eq!(eq("a", "ab"), false);
assert_eq!(eq("ab", "a"), false);
protocol PARTIAL_CMP
if value < b { }

Perform a partial ordered comparison between two strings.

Examples

assert!("a" < "ab");
assert!("ab" > "a");
assert!("a" == "a");

Using explicit functions:

use std::cmp::Ordering;
use std::ops::partial_cmp;

assert_eq!(partial_cmp("a", "ab"), Some(Ordering::Less));
assert_eq!(partial_cmp("ab", "a"), Some(Ordering::Greater));
assert_eq!(partial_cmp("a", "a"), Some(Ordering::Equal));
protocol CMP
if value < b { }

Perform a totally ordered comparison between two strings.

Examples

use std::cmp::Ordering;
use std::ops::cmp;

assert_eq!(cmp("a", "ab"), Ordering::Less);
assert_eq!(cmp("ab", "a"), Ordering::Greater);
assert_eq!(cmp("a", "a"), Ordering::Equal);
protocol HASH
let $out = hash(value)

Hash the string.

Examples

use std::ops::hash;

let a = "hello";
let b = "hello";

assert_eq!(hash(a), hash(b));
protocol DISPLAY_FMT
format!("{}", value)

Write a display representation of a string.

Examples

println!("{}", "Hello");
protocol DEBUG_FMT
format!("{:?}", value)

Write a debug representation of a string.

Examples

println!("{:?}", "Hello");
protocol LT
if $a < $b { }

The protocol behind the < operator.

protocol LE
if $a <= $b { }

The protocol behind the <= operator.

protocol GT
if $a > $b { }

The protocol behind the > operator.

protocol GE
if $a >= $b { }

The protocol behind the >= operator.

protocol MIN
$a.min($b)

The implementation protocol for the PartialOrd::min method.

protocol MAX
$a.max($b)

The implementation protocol for the PartialOrd::max method.