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.
- Rust
- JS
- Python
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())
}
import StellarSdk = require('@stellar/stellar-sdk');
// Example string
const stringValue = 'Hello, Stellar!';
// Convert the string to bytes format
const byteValue = Buffer.from(stringValue, 'utf-8');
import stellar_sdk
string_value.encode()
string_value
is the string value to be converted to bytes..encode()
is a method that converts the string to bytes.
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.
- Rust
- JS
use soroban_sdk::{Address, Env, String};
pub fn string_to_address(string: String) -> Address {
Address::from_string(&string)
}
const StellarSdk = require("@stellar/stellar-sdk");
const stringToAddress = StellarSdk.Address.fromString(stellarAddress);
stellarAddress
is the string value to be converted to an address.StellarSdk.Address.fromString()
is a method that converts a string to an address.
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.
- Rust
- JS
- Python
use soroban_sdk::{String, Env, Val};
pub fn string_to_val(env: &Env, string: String) -> Val {
string.to_val()
}
import StellarSdk from "@stellar/stellar-sdk";
// Example string value
const stringValue = "Hello, Stellar!";
// Convert the string to ScVal
const stringToScVal = StellarSdk.xdr.ScVal.scvString(stringValue);
import stellar_sdk
string_to_sc_val = stellar_sdk.scval.to_string(string_value)
string_value
is the string value to be converted to an ScValstellar_sdk.scval.to_string()
converts the string value to an ScVal