0

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. – smarx Jun 28 '18 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. – Ruham Jun 28 '18 at 2:23
  • @smarx That may not be the best solution, but I need that. Could you please help? – Ruham Jun 28 '18 at 2:52
  • There's a library for string manipulation github.com/Arachnid/solidity-stringutils. – Ismael Jun 28 '18 at 23:18
1

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. – Ruham Jun 29 '18 at 5:07
  • please post this as a new question and let me know. – Jaime Jun 29 '18 at 6:18

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.