1

hello guys this is my code and i want to reverse a string with solidity :

function reverseValue(string _base) internal returns(string){
        bytes memory _baseBytes = bytes(_base);

        string memory _tempValue = new string(_baseBytes.length);
        bytes memory _newValue = bytes(_tempValue);

        for(uint i=_baseBytes.length;i<=0;i--){
            _newValue[_baseBytes.length - i] = _baseBytes[i];
        }

        return string(_newValue);
    }

but the only result is this code below : 0:string : \u0000\u0000\u0000\u0000\u0000\u0000

i think i wrote my code right but i cant find the problem ... tnx to help me :)

1 Answer 1

2

i found this answer and this is the right code :

function reverseValue(string _base) internal returns(string){
        bytes memory _baseBytes = bytes(_base);
        assert(_baseBytes.length > 0);

        string memory _tempValue = new string(_baseBytes.length);
        bytes memory _newValue = bytes(_tempValue);


        for(uint i=0;i<_baseBytes.length;i++){
            _newValue[ _baseBytes.length - i - 1] = _baseBytes[i];
        }

        return string(_newValue);
    }

now the result for this particular code is :

_base : "shahab" -> result : 0 : string : "bahahas"
2
  • Strings in solidity are presumed to be encoded with utf-8. Many international characters are longer than one byte in utf-8, so reversing the bytes naively will likely produce a corrupted (or non-decodable) result.
    – carver
    Feb 5, 2018 at 16:59
  • @carver thank you dear friend i'm just started to learning solidity and this was a great tip ... tnx ... but can you tell me some practices for learning solidity in real world..?? Feb 5, 2018 at 19:27

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.