The String type
is a wrapper around Vec<u8> that handles UTF-8 strings allocated inside
the heap memory.
See Table 1 for a partial list of its methods and String for the full list.
Table 1:Some methods of String
Method | Description |
|---|---|
| Returns a byte slice. |
| Returns a mutable string slice. |
| Returns a string slice. |
| Returns the instance’s capacity in bytes. |
| Removes all characters. |
| Removes a range of characters and returns an iterator on them. |
| Creates a string from a literal string. |
| Inserts a character at the specified index. |
| Inserts a string slice at the specified index. |
| Converts (and consumes) the |
| Returns |
| Returns the number of bytes of the string. |
| Creates an empty string. |
| Removes and returns the last character. |
| Appends one character to the string. |
| Appends a string slice to the string. |
| Removes and returns the character at the specified index. |
| Replaces a range of characters by a string slice. |
| Reserves additional memory space (i.e.: increases the capacity). |
| Shrinks the capacity to specified size. |
| Shrinks the capacity in order to match length. |
| Shortens the string to the specified length. |
| Creates a new empty |
18.2.1New empty string¶
The new() method builds a new empty string:
let s = String::new();
sCouldn't automatically determine type of variable `s`.
Please give it an explicit type.18.2.2New instance from literal string¶
Using the from() method, we can build a String instance from a literal
string:
let s = String::from("abc");
s18.2.3Appending to a String object¶
The push() method appends a character to a string:
let mut s = String::new();
s.push('a'); // Append a single character
sThe push_str() method appends a string slice to a string:
let mut s = String::new();
s.push_str("def");
s18.2.4format!() macro¶
The format!() macro allows
to build a String instance using formatting codes from
fmt module.
Plain literal strings are transformed into String objects:
let s = format!("My string");
sHowever the real advantage of the format!() macro is the formatting
instructions inserted with curly brackets ({}).
In the following example we use the curly brackets notation to insert
the value of the variable n:
let n = 10;
let s = format!("Number: {n}");
sIn the following example, we use format!() to concatenate two strings:
let s1 = String::from("abc");
let s2 = String::from("def");
let s3 = format!("{s1}{s2}");
s3String alignment:
let s = "abc";
format!("#{s:<7}#{s:.<7}#{s:^7}#{s:>7}#")Formatting a zero padded integer:
let n = 16;
format!("{n:05}")Formatting a floating-point number:
let x = 1893.7834;
format!("{x} {x:.5} {x:.2} {x:.3e} {x:.2E}")Formatting an integer into binary, octal or hexadecimal:
let n = 170;
format!("{n:b} {n:o} {n:x} {n:X} {n:04x}")Formatting a complex object using the Debug formatter:
let t = (1.5, "abc", true);
format!("{t:?}")