Created
September 27, 2021 17:34
-
-
Save nathan-websculpt/398b0da3581a177d2abdd2356c206d5b to your computer and use it in GitHub Desktop.
Compare and Concat strings in solidity
This file contains 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
// SPDX-License-Identifier: GPL-3.0 | |
pragma solidity >=0.7.0 <0.9.0; | |
contract StringTesting { | |
function stringCompare(string calldata _inputOne, string calldata _inputTwo) external pure returns (bool r) { | |
bool rslt; | |
//Solidity does not offer string comparison | |
//Will produce TypeError: operator == not compatible with types string calldata and string calldata | |
//rslt = (_inputOne == _inputTwo); | |
//string memory testOne = "test"; | |
//string memory testTwo = "test"; | |
//Will produce TypeError: operator == not compatible with types string memory and string memory | |
//rslt = (testOne == testTwo); | |
rslt = (keccak256(abi.encodePacked(_inputOne)) == keccak256(abi.encodePacked(_inputTwo))); | |
return rslt; | |
} | |
function stringCompareBytes(string calldata _inputOne, string calldata _inputTwo) external pure returns (bool r) { | |
bool rslt; | |
rslt = (keccak256(bytes(_inputOne)) == keccak256(bytes(_inputTwo))); | |
return rslt; | |
} | |
function stringConcat(string calldata _inputOne, string calldata _inputTwo) external pure returns (string memory r) { | |
string memory rslt = string(abi.encodePacked(_inputOne, _inputTwo)); | |
return rslt; | |
} | |
function stringConcatBytes(string calldata _inputOne, string calldata _inputTwo) external pure returns (string memory r) { | |
string memory rslt = string(bytes.concat(bytes(_inputOne), bytes(_inputTwo))); | |
return rslt; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example code for this blog post