String concatenation in solidity?
You can't concatenate strings. You also can not check equals (str0 == str1
) yet. The string type was just recently added back to the language so it will probably take a while until all of this works. What you can do (which they recently added) is to use strings as keys for mappings.
The concatenation you're pointing to is how storage addresses are computed based on field types and such, but that's handled by the compiler.
An answer from the Ethereum Stack Exchange:
A library can be used, for example:
import "github.com/Arachnid/solidity-stringutils/strings.sol";
contract C {
using strings for *;
string public s;
function foo(string s1, string s2) {
s = s1.toSlice().concat(s2.toSlice());
}
}
Use the above for a quick test that you can modify for your needs.
Since concatenating strings needs to be done manually for now, and doing so in a contract may consume unnecessary gas (new string has to be allocated and then each character written), it is worth considering what's the use case that needs string concatenation?
If the DApp can be written in a way so that the frontend concatenates the strings, and then passes it to the contract for processing, this could be a better design.
Or, if a contract wants to hash a single long string, note that all the built-in hashing functions in Solidity (sha256
, ripemd160
, sha3
) take a variable number of arguments and will perform the concatenation before computing the hash.