3

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?

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

3 Answers3

5

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

Jaime
  • 8,340
  • 1
  • 12
  • 20
  • 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. – Ruham Jun 29 '18 at 05:07
  • please post this as a new question and let me know. – Jaime Jun 29 '18 at 06:18
  • this just reverts for me... – Jim May 19 '22 at 00:09
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

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

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 &quot;string-utils-lib/StringUtilsLib.sol&quot;

contract UseContract{
    using StringUtilsLib for string;

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

      //Expected cdef
  }
}

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