Strings

Sui 2024 adds conversions on vector<u8>: b"hi".to_string() and b"hi".to_ascii_string().

10.1 UTF-8 strings: std::string

Sui 2024 adds conversions on vector<u8>: b"hi".to_string() and b"hi".to_ascii_string().

use std::string::{Self, String};

let mut s: String = string::utf8(b"Hello");   // aborts if bytes are not valid UTF-8
s.append(string::utf8(b", Move!"));
s.append_utf8(b" 🚀");
let n = s.length();                            // length in BYTES, not characters
let sub = s.sub_string(0, 5);                  // byte indices; must be on char boundaries
let bytes: &vector<u8> = s.as_bytes();         // older name: bytes()
let maybe = string::try_utf8(b"\xFF");         // Option<String>: none here
let empty = s.is_empty();
let idx = s.index_of(&string::utf8(b"Move"));  // byte index or length if absent

10.2 ASCII strings: std::ascii

Sui uses ascii::String for things like coin symbols and URLs (sui::url::Url).

use std::ascii;

let a: ascii::String = ascii::string(b"TICKER");   // aborts on non-ASCII
let maybe = ascii::try_string(b"ok");
let upper = a.to_uppercase();                       // available in recent std versions
let as_utf8: std::string::String = a.to_string();

10.3 Strings as entry/PTB arguments

Both chains accept String (and on Sui ascii::String) as pure arguments to entry/public functions; the SDK encodes them as BCS byte vectors.

10.4 Integer to string

// Sui
let s = 42u64.to_string();
// Aptos
let s = aptos_std::string_utils::to_string(&42u64);   // also format1!/format2! helpers