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)

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).

  • Here's a fiddle so you can play around with it: ethfiddle.com/-IaBg6dld7 – James Duffy Nov 24 '17 at 9:30
  • Thank you, Nicci and James for making the community better. I was not aware of ethfiddle. Very helpful. – Titu Nov 24 '17 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.