Skip to main content

Convert a string to other types

Strings are a sequence of characters used to represent readable text. They are used to store and manipulate text-based information such as function names, arguments, key-value data and interfacing with external systems. Strings may often need to be converted to other data types for efficient processing and storage.

String to bytesNโ€‹

Some systems use binary formats where data needs to be represented as a fixed-length byte array for storage or processing. For example, fixed-length hashes or identifiers. Converting strings to a fixed byte size ensures that the data fits the required size constraints.

use soroban_sdk::{String, BytesN, Env, FromVal};

pub fn string_to_bytesN(env: &Env, string: String) -> BytesN<32> {
BytesN::from_val(env, &string.to_val())
}

String to addressโ€‹

An address received in a user input may be of string type and you would need to convert it to an address type to perform validations, transactions, or other operations within your smart contract.

use soroban_sdk::{Address, Env, String};

pub fn string_to_address(string: String) -> Address {
Address::from_string(&string)
}

String to ScValโ€‹

When calling functions or methods that expect ScVal types, you need to convert your string data to ScVal to make the call successful. For example, if your smart contract needs to store or manipulate a user input string within its state or use it as part of its logic, you would convert the string to an ScVal type to integrate it with the contract's operations.

use soroban_sdk::{String, Env, Val};

pub fn string_to_val(env: &Env, string: String) -> Val {
string.to_val()
}