# Solidity: extracting (slicing) characters from a string

Perhaps a double, but I couldn't find an answer here, and neither in strings library.

I have a string public string = "ABCDEFG"

I need to put together a function that iterates through the characters of the string and returns the characters that are in between the input numbers.

for example, function getSlice(uint256 begin, uint256 end) would return CDE if passed 2 and 6.

What would be the best way to create such a function?

• Why are you doing this in Solidity? It seems like something that would be much better done off-chain. Jun 28, 2018 at 1:50
• I know, but this is a result of an Oraclize callback function, and I need to slice it to use in another function. Jun 28, 2018 at 2:23
• @smarx That may not be the best solution, but I need that. Could you please help? Jun 28, 2018 at 2:52
• There's a library for string manipulation github.com/Arachnid/solidity-stringutils.
– Ismael
Jun 28, 2018 at 23:18

You can do this:

pragma solidity 0.4.24;

contract test{

function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) {
bytes memory a = new bytes(end-begin+1);
for(uint i=0;i<=end-begin;i++){
a[i] = bytes(text)[i+begin-1];
}
return string(a);
}

}

The variable text is the text that you want to slice.

Hope it helps

• Could you please help me with a modification of this function? I will always have 14, 15 or 16 character strings. The issue is - I don't know when I will receive which type of the string. However, I do know, that I want to drop all the characters of the string before the 12, so that I end up with the last 2, 3 or 4 characters. Jun 29, 2018 at 5:07
• please post this as a new question and let me know. Jun 29, 2018 at 6:18
• this just reverts for me...
– Jim
May 19, 2022 at 0:09

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

i just developed a solidity library that solves this problem and possibly almost any other you might have with strings, it's called 'string-utils-lib', you can check it on my github String Utils Lib. With the library, you can create a substring from the string this way:

pragma solidity ^0.8.18

import {StringUtilsLib} from "string-utils-lib/StringUtilsLib.sol"

contract UseContract{
using StringUtilsLib for string;

function spliceStringExample() public pure returns(string memory){
string memory a = "abcdefg";
return a.substring(2, 5);

//Expected cdef
}
}

The substring() function would return a new string with the specified points