【问题标题】:how to reverse a string in solidity?如何牢固地反转字符串?
【发布时间】:2018-07-13 23:56:18
【问题描述】:

大家好,这是我的代码,我想用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);
    }

但唯一的结果是下面的代码: 0:string : \u0000\u0000\u0000\u0000\u0000\u0000

我认为我的代码写对了,但我找不到问题... tnx 来帮助我:)

【问题讨论】:

    标签: solidity


    【解决方案1】:

    我找到了这个答案,这是正确的代码:

    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);
        }
    

    现在这个特定代码的结果是:

    _base : "shahab" -> result : 0 : string : "bahahas"
    

    【讨论】:

    • solidity 中的字符串被假定为使用 utf-8 编码。许多国际字符在 utf-8 中的长度超过一个字节,因此天真地反转字节可能会产生损坏(或不可解码)的结果。
    • @carver 谢谢亲爱的朋友,我刚开始学习solidity,这是一个很好的提示... tnx ...但是你能告诉我一些在现实世界中学习solidity 的做法吗? ??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 2012-11-16
    • 2023-03-24
    • 2023-02-01
    • 2011-06-14
    相关资源
    最近更新 更多