10

I am looking for a way to get substring of a String. I am looking for an equivalent of this Java method. I am ok to use libraries but did not find it in solidity-stringutils.

public String substring(int startIndex, int endIndex)
Titu
  • 379
  • 3
  • 13

3 Answers3

12

The solidity documentation states, that there is no built in string manipulation available. Nevertheless, we can convert a string to a byte array and do the manipulation manually:

function substring(string str, uint startIndex, uint endIndex) constant returns (string) {
    bytes memory strBytes = bytes(str);
    bytes memory result = new bytes(endIndex-startIndex);
    for(uint i = startIndex; i < endIndex; i++) {
        result[i-startIndex] = strBytes[i];
    }
    return string(result);
}

Disclaimer: this method works for ASCII strings, but not for characters that are encoded with multiple bytes in UTF-8 (e.g. umlaute).

T. Nicci
  • 136
  • 1
  • 3
6

Update for Solidity 0.8.0 versions

function substring(string memory str, uint startIndex, uint endIndex) public pure returns (string memory ) {
    bytes memory strBytes = bytes(str);
    bytes memory result = new bytes(endIndex-startIndex);
    for(uint i = startIndex; i < endIndex; i++) {
        result[i-startIndex] = strBytes[i];
    }
    return string(result);
}
Extrange planet
  • 685
  • 5
  • 11
0

Here's a shorter, gas-efficient answer without for loops:

function trim(string calldata str, uint start, uint end) external pure returns(string memory) {
    return str[start:end];
}

This takes a string and start and end positions and returns a substring.

Adam Boudj
  • 2,361
  • 1
  • 8
  • 21