{

How to find the length of a string in solidity| Solidity by Example


This tutorial finds the string length in solidity with examples. It checks the number of characters in a given string and returns the length of a string.

For example, given string is hello, the output is 5.

In solidity, the string is a group of characters stored inside an array and stores the data in bytes.

There is no length method in string type.

How to find string length in solidity.

First, convert string to bytes using the bytes(string) method.

bytes.length returns the uint type.

uint is alias for uint256.

Here is a steps to get the length

input string(string type)=> bytes(bytes) => length => uint

Here is a code for Find character count in string solidity.

 // SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.7; 

contract StringTest {
    function mine(string memory s) public pure returns ( uint256) {
        return bytes(s).length;
        }
}

Input: { “string s”: “hello” }

Output:
```json
{
    "0": "uint256: 5"
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.