LoginSignup
5
0

More than 5 years have passed since last update.

Solidityで文字列のlengthを取得する方法

Last updated at Posted at 2018-12-26

前提

Solidity v0.5.0 において
現状、文字列(String)にはlengthメソッドが存在しない。
しかしながらbytesにはlengthメソッドが存在している。

方法

そのため、文字列を一度bytesに変換してから、そのbytesのlength(uint)を取得することで文字列のlengthを取得する。
string -> bytes -> uint

環境

  • Solidity 0.5.0

サンプルコード

 以下にそのコードを記載しているので、Remixなどで試していただきたい。
例えば、"hoge"という文字列を与えると、lenは4になる。

pragma solidity ^0.5.0;
contract StrLen {   
    function getStrLen(string memory _str) public returns(uint) {
        uint len = bytes(_str).length;
        return len;
    }   
}

サンプルを動かした結果

getStrLen("hoge")

len: 4

スクリーンショット 2018-12-26 15.32.38.png

ただし、文字列に平仮名などを与えると当然想定外の数値が返ってくるので注意。

getStrLen("ぽよ")

len: 6

スクリーンショット 2018-12-26 15.33.10.png

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0