如何可靠地反转字符串?
how to reverse a string in solidity?
大家好,这是我的代码,我想用 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 帮助我:)
我找到了这个答案,这是正确的代码:
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 反转字符串:
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 帮助我:)
我找到了这个答案,这是正确的代码:
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"