Get the First Character of a String in Solidity
In some cases, it is necessary to get the first character of a string in solidity. You need to perform the following steps:
- convert the string into a bytes array.
- select the first byte from it and
- 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);
}
}