Created
February 27, 2022 13:58
-
-
Save samigabor/c5ec50f6bf47dcf35504660a08ef63c7 to your computer and use it in GitHub Desktop.
String length in Solidity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // SPDX-License-Identifier: UNLICENSED | |
| // Source: https://github.com/ensdomains/ens-contracts/blob/master/contracts/ethregistrar/StringUtils.sol | |
| pragma solidity >=0.8.4; | |
| library StringUtils { | |
| /** | |
| * @dev Returns the length of a given string | |
| * | |
| * @param s The string to measure the length of | |
| * @return The length of the input string | |
| */ | |
| function strlen(string memory s) internal pure returns (uint256) { | |
| uint256 len; | |
| uint256 i = 0; | |
| uint256 bytelength = bytes(s).length; | |
| for (len = 0; i < bytelength; len++) { | |
| bytes1 b = bytes(s)[i]; | |
| if (b < 0x80) { | |
| i += 1; | |
| } else if (b < 0xE0) { | |
| i += 2; | |
| } else if (b < 0xF0) { | |
| i += 3; | |
| } else if (b < 0xF8) { | |
| i += 4; | |
| } else if (b < 0xFC) { | |
| i += 5; | |
| } else { | |
| i += 6; | |
| } | |
| } | |
| return len; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment