How to find the length of a string in solidity| Solidity by Example
This tutorial explains how to determine the string length in Solidity with examples. It checks the number of characters in a given string and returns the length of the string.
For instance, if the string is hello
, the output is 5.
In Solidity, a string
is a group of characters stored inside an array, and the data is stored in bytes.
Notably, there is no built-in length method for the string
type.
How to find string length in solidity
First, convert the string to bytes using the bytes(string)
method.
The bytes.length
returns a value of type uint.
uint
is an alias for uint256
.
Here are the 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:
{
"0": "uint256: 5"
}