String
7 methodsA UTF-8-encoded, growable string. It is the owned version of &str.
String::new() -> StringCreates a new empty String.
Returns
String
Example
rust
let s = String::new();
assert!(s.is_empty());String::from(s: &str) -> StringConverts a &str into a String, copying the data.
Parameters
| Name | Type | Description |
|---|---|---|
| s | &str | String 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
| Name | Type | Description |
|---|---|---|
| s2 | &str | String 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
| Name | Type | Description |
|---|---|---|
| ch | char | Character to append. |
Returns
()
Example
rust
let mut s = String::from("abc");
s.push('1');
s.push('2');
assert_eq!(s, "abc12");s.len() -> usizeReturns 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 bytess.as_str() -> &strExtracts 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) -> StringReplaces all matches of a pattern with another string, returning a new String.
Parameters
| Name | Type | Description |
|---|---|---|
| from | &str | Pattern to replace. |
| to | &str | Replacement string. |
Returns
String
Example
rust
let s = String::from("this is old");
assert_eq!(s.replace("old", "new"), "this is new");