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
- JavaScript
- Python
use soroban_sdk::{Bytes, String};
pub fn string_to_bytes(string: String) -> Bytes {
Bytes::from(string)
}
// Example string
const stringValue = "Hello, Stellar!";
// Convert the string to bytes format
const byteValue = Buffer.from(stringValue, "utf-8");
# Example string
string_value = "Hello, Stellar!"
# Convert the string to bytes format
string_value.encode()
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
- JavaScript
- Python
use soroban_sdk::{Address, Env, String};
pub fn string_to_address(string: String) -> Address {
Address::from_string(&string)
}
const StellarSdk = require("@stellar/stellar-sdk");
// Example Stellar address
const stellarAddress =
"GCM5WPR4DDR24FSAX5LIEM4J7AI3KOWJYANSXEPKYXCSZOTAYXE75AFN";
// Create an Address object from string
const address = new StellarSdk.Address(stellarAddress);
// Convert the address back to string
const addressToString = address.toString();
from stellar_sdk import Address
# Example Stellar address
stellar_address = "GCM5WPR4DDR24FSAX5LIEM4J7AI3KOWJYANSXEPKYXCSZOTAYXE75AFN"
# Create an Address object from string
address = Address(stellar_address)
# Convert the address back to string
address_to_string = address.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
- JavaScript
- Python
use soroban_sdk::{String, Val};
pub fn string_to_val(string: String) -> Val {
Val::from(string)
}
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
# Example string value
string_value = "Hello, Stellar!"
# Convert the string to ScVal
string_to_sc_val = stellar_sdk.scval.to_string(string_value)