Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

as_bytes()

Returns a byte slice.

as_mut_str()

Returns a mutable string slice.

as_str()

Returns a string slice.

capacity()

Returns the instance’s capacity in bytes.

clear()

Removes all characters.

drain(r)

Removes a range of characters and returns an iterator on them.

from(s)

Creates a string from a literal string.

insert(i, c)

Inserts a character at the specified index.

insert_str(i, s)

Inserts a string slice at the specified index.

into_bytes()

Converts (and consumes) the String into a Vec<u8>.

is_empty()

Returns true if the instance contains no character.

len()

Returns the number of bytes of the string.

new()

Creates an empty string.

pop()

Removes and returns the last character.

push(c)

Appends one character to the string.

push_str(s)

Appends a string slice to the string.

remove(i)

Removes and returns the character at the specified index.

replace_range(r, s)

Replaces a range of characters by a string slice.

reserve(n)

Reserves additional memory space (i.e.: increases the capacity).

shrink_to(n)

Shrinks the capacity to specified size.

shrink_to_fit()

Shrinks the capacity in order to match length.

truncate(n)

Shortens the string to the specified length.

with_capacity(n)

Creates a new empty String with the specified capacity.

18.2.1New empty string

The new() method builds a new empty string:

Couldn'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:

18.2.3Appending to a String object

The push() method appends a character to a string:

The push_str() method appends a string slice to a string:

18.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:

However 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:

In the following example, we use format!() to concatenate two strings:

String alignment:

Formatting a zero padded integer:

Formatting a floating-point number:

Formatting an integer into binary, octal or hexadecimal:

Formatting a complex object using the Debug formatter:

see solution

see solution