TExcelTAD
Home › Solidity › Strings & Bytes

Strings & Bytes

Text and raw binary data use two dynamically sized types: string for UTF-8 text and bytes for arbitrary bytes. They are close relatives: a string is essentially bytes without index access or length. Solidity's string support is deliberately minimal, because string processing costs gas.

Feature string bytes
Contents UTF-8 text any bytes
.length no (convert to bytes first) yes
Index s[i] no yes (returns bytes1)
push/pop (storage) no yes
Concatenate string.concat(a, b) bytes.concat(a, b)
Compare with == no no

Basic operations

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    function main() external pure {
        string memory first = "Grace";
        string memory last = "Hopper";

        string memory full = string.concat(first, " ", last);
        console.log(full);
        console.log("bytes in name:", bytes(full).length);

        bytes memory raw = bytes(full);
        console.logBytes1(raw[0]);                 // 'G' is 0x47
        console.log("first letter:", string(abi.encodePacked(raw[0])));
    }
}
Grace Hopper
bytes in name: 12
0x47
first letter: G

Length counts bytes, not characters

UTF-8 uses 1 to 4 bytes per character, so bytes(s).length is the byte length. Non-ASCII text needs the unicode prefix in literals:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    function main() external pure {
        string memory plain = "cafe";
        string memory accented = unicode"café";
        string memory rocket = unicode"🚀";

        console.log(plain, bytes(plain).length);
        console.log(accented, bytes(accented).length);
        console.log(rocket, bytes(rocket).length);
    }
}
cafe 4
café 5
🚀 4

Comparing strings

== doesn't work on strings. Compare their hashes: equal strings always have equal keccak256 hashes.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    function same(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }

    function main() external pure {
        console.log("same(apple, apple):", same("apple", "apple"));
        console.log("same(apple, Apple):", same("apple", "Apple"));
        console.log("same('', ''):", same("", ""));
    }
}
same(apple, apple): true
same(apple, Apple): false
same('', ''): true

Numbers to strings and character tricks

There's no built-in toString. Writing one is a great exercise in working with bytes: produce the digits from right to left into a buffer.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    function toString(uint256 value) internal pure returns (string memory) {
        if (value == 0) return "0";
        uint256 digits;
        for (uint256 v = value; v != 0; v /= 10) digits++;
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits--;
            buffer[digits] = bytes1(uint8(48 + value % 10));   // 48 is '0'
            value /= 10;
        }
        return string(buffer);
    }

    function toUpper(string memory s) internal pure returns (string memory) {
        bytes memory b = bytes(s);
        for (uint256 i = 0; i < b.length; i++) {
            if (b[i] >= "a" && b[i] <= "z") {
                b[i] = bytes1(uint8(b[i]) - 32);
            }
        }
        return string(b);
    }

    function main() external pure {
        string memory label = string.concat("Order #", toString(1042), " for ", toUpper("alice"));
        console.log(label);
    }
}
Order #1042 for ALICE

Production code usually imports a battle-tested helper such as OpenZeppelin's Strings.toString(uint256) rather than writing its own.

Dynamic bytes in storage

A storage bytes value can grow with push, which makes it a compact byte buffer:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    bytes public log;

    function main() external {
        log.push(0x48);   // H
        log.push(0x69);   // i
        console.log(string(log), log.length);
        console.logBytes(log);
    }
}
Hi 2
0x4869

Gas tips

  • Strings are expensive in storage: each 32 bytes is one slot. Short, fixed labels fit in a bytes32 (see Addresses & Fixed Bytes).
  • Prefer emitting long text in events over storing it.
  • Error messages in require are stored in the bytecode; custom errors (Custom Errors lesson) are cheaper.

Test yourself

What is bytes(unicode"café").length?

  1. 4
  2. 5
  3. 8
  4. It doesn't compile

Which function joins two strings in Solidity 0.8.12+?

  1. a + b
  2. string.concat(a, b)
  3. a.append(b)
  4. concat(a, b)

How do you read the first byte of a string memory s?

  1. s[0]
  2. bytes(s)[0]
  3. s.charAt(0)
  4. s.first