Contents
String in Solidity
Like most of the programming languages, Solidity also provides String data type. The string can be initialized by using both single quotes or double quotes as shown below.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; contract DemoContract { // using double quotes string public str1 = "Hello World"; // using single quotes string public str2 = 'Hello World'; }
It is very important to note that in solidity by default the string variable is assumed to be a state variable that is persisted on the Ethereum blockchain. As a result, it also incurs gas fees.
If we want to declare a string variable inside a function, we have to explicitly use the memory keyword as shown below. This tells the compiler to save it in memory and not in storage.
If memory keyword is not used then the compiler will throw an error – TypeError: Data location must be “storage”, “memory” or “calldata” for variable, but none was given.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; contract DemoContract { function TestFunction() pure public returns(string memory) { // local variable string memory department = "Marketing"; return department; } }
It may appear that the string in Solidity will have the regular methods and properties for common operations like string concatenation, string comparison, etc. but this is not the case. There are however some ABI encoding functions that can be used as a workaround. Let us see some examples.
String Comparision in Solidity
The string comparison in solidity can be done by using abi.encodePacked() function and applying cryptographic hash keccak256 function. If the string is the same it will produce the same hash else it will differ.
Below show one such example of string comparison in Solidity.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; contract DemoContract { string s1 = 'Hello'; string s2 = 'Hello'; bool public isEqual; function compare() public { isEqual = keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2)); } }
Output
0:bool: true
String Concatenation in Solidity
The string concatenation in solidity is done by using abi.encodePacked() function as shown in the below example.
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; contract DemoContract { string s1 = 'Hello'; string s2 = ' World'; string public s3; function concatenate() public { s3 = string(abi.encodePacked(s1,s2)); } }
Output
0:string: Hello World