-
-
Save ottodevs/c43d0a8b4b891ac2da675f825b1d1dbf to your computer and use it in GitHub Desktop.
Ethereum/Solidity toLower() equivalent, to transform strings to lowercase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.11; | |
contract StringToLower { | |
function _toLower(string str) internal returns (string) { | |
bytes memory bStr = bytes(str); | |
bytes memory bLower = new bytes(bStr.length); | |
for (uint i = 0; i < bStr.length; i++) { | |
// Uppercase character... | |
if ((bStr[i] >= 65) && (bStr[i] <= 90)) { | |
// So we add 32 to make it lowercase | |
bLower[i] = bytes1(int(bStr[i]) + 32); | |
} else { | |
bLower[i] = bStr[i]; | |
} | |
} | |
return string(bLower); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This gives unexpected behavior when the string that was passed in
_toLowerCase
is referenced later in the code, because_toLowerCase
doesn't only transform the output, but also modifies the original string and its bytes in the memory.So here's a fixed "transform string to lower case" version for Solidity above
^0.5.0
(that won't modify the original string in the memory):