Skip to content

Rust std::string::String API

Rust's String — a growable, owned UTF-8 encoded string type, heap-allocated and mutable.

1 class · 7 methods

String

7 methods

A UTF-8-encoded, growable string. It is the owned version of &str.

String::new() -> String

Creates a new empty String.

Returns

String

Example

rust
let s = String::new();
assert!(s.is_empty());
String::from(s: &str) -> String

Converts a &str into a String, copying the data.

Parameters

NameTypeDescription
s&strString slice to convert.

Returns

String

Example

rust
let s = String::from("hello");
assert_eq!(s, "hello");
s.push_str(s2: &str)

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

Parameters

NameTypeDescription
s2&strString slice to append.

Returns

()

Example

rust
let mut s = String::from("foo");
s.push_str("bar");
assert_eq!(s, "foobar");
s.push(ch: char)

Appends the given char to the end of this String.

Parameters

NameTypeDescription
chcharCharacter to append.

Returns

()

Example

rust
let mut s = String::from("abc");
s.push('1');
s.push('2');
assert_eq!(s, "abc12");
s.len() -> usize

Returns the length of this String, in bytes, not chars or graphemes.

Returns

usize

Example

rust
let s = String::from("hello");
assert_eq!(s.len(), 5);

let nihongo = String::from("日本語");
assert_eq!(nihongo.len(), 9); // 3 chars * 3 bytes
s.as_str() -> &str

Extracts a string slice containing the entire String.

Returns

&str

Example

rust
let s = String::from("hello");
let slice: &str = s.as_str();
assert_eq!(slice, "hello");
s.replace(from: &str, to: &str) -> String

Replaces all matches of a pattern with another string, returning a new String.

Parameters

NameTypeDescription
from&strPattern to replace.
to&strReplacement string.

Returns

String

Example

rust
let s = String::from("this is old");
assert_eq!(s.replace("old", "new"), "this is new");