Get the First Character of a String in Solidity

Published by Mario Oettler on

Last Updated on 12. June 2023 by Mario Oettler

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:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: