Skip to main content

Mojo module

string

The core String type implementation for Mojo.

This module provides the primary String type and its fundamental operations. The String type is a mutable string, and is designed to handle UTF-8 encoded text efficiently while providing a safe and ergonomic interface for string manipulation.

Related types:

  • StringSlice. A non-owning view of string data, which can be either mutable or immutable.
  • StaticString. An alias for an immutable constant StringSlice.
  • StringLiteral. A string literal. String literals are compile-time values. For use at runtime, you usually want wrap a StringLiteral in a String (for a mutable string) or StaticString (for an immutable constant string).

Key Features:

  • Short string optimization (SSO) and lazy copying of constant string data.
  • O(1) copy operation.
  • Memory-safe string operations.
  • Efficient string concatenation and slicing.
  • String-to-number conversions ( atof(), atol()).
  • Character code conversions ( chr(), ord()).
  • String formatting with format().

The String type has Unicode support through UTF-8 encoding. A handful of operations are known to not be Unicode / UTF-8 compliant yet, but will be fixed as time permits.

This type is in the prelude, so it is automatically imported into every Mojo program.

Example:

# String creation and basic operations
var s1 = String("Hello")
var s2 = String("World")
var combined = s1 + " " + s2 # "Hello World"

# String-to-number conversion
var num = atof("3.14")
var int_val = atol("42")

# Character operations
var char = chr(65) # "A"
var code = ord("A") # 65

# String formatting
print(String("Codepoint {} is {}").format(code, char)) # Codepoint 65 is A

# ASCII utilities
var ascii_str = ascii("Hello") # ASCII-only string
# String creation and basic operations
var s1 = String("Hello")
var s2 = String("World")
var combined = s1 + " " + s2 # "Hello World"

# String-to-number conversion
var num = atof("3.14")
var int_val = atol("42")

# Character operations
var char = chr(65) # "A"
var code = ord("A") # 65

# String formatting
print(String("Codepoint {} is {}").format(code, char)) # Codepoint 65 is A

# ASCII utilities
var ascii_str = ascii("Hello") # ASCII-only string

Structs

Functions

  • ascii: Get the ASCII representation of the object.
  • atof: Parses the given string as a floating point and returns that value.
  • atol: Parses and returns the given string as an integer in the given base.
  • chr: Returns a String based on the given Unicode code point. This is the inverse of the ord() function.
  • ord: Returns an integer that represents the codepoint of a single-character string.

Was this page helpful?