Get the First Character of a String in Solidity

Published by Mario Oettler on

In some cases, it is necessary to get the first character of a string in solidity. You need to perform the following steps:

  1. convert the string into a bytes array.
  2. select the first byte from it and
  3. convert it back to string.

If you want to get another character, just choose the index accordingly.

To get the last char of a string, you can use

bytes(yourString).length

Example

The following code shows how to get the first char of a string:

pragma solidity 0.8.20;

contract StringChar{

    function getFirstChar(string memory _originString) public view returns (string memory _firstChar){
        bytes memory firstCharByte = new bytes(1);
        firstCharByte[0] = bytes(_originString)[0];
        return string(firstCharByte);
    }
}
Categories: