solidity string concatenation

If you want to start learning Ethereum DApp development right away, you can visit the excellent online interactive tutorial provided by Huizhi.com: -Introduction
to Ethereum DApp Practical Development -Decentralized E - commerce DApp Practical Development

When you start learning to develop Ethereum smart contracts with solidity, you will soon encounter a problem:

How to concatenate strings in solidity?

As you may have tried, the following code tries to join two strings using the addition operator, but it doesn't work:

var str = 'asdf'
var b = str + 'sdf'

In fact, according to the official documents of solidity, currently in solidity, we need to implement the string splicing function ourselves.

splicing string implementation code

For example, the following code implements the concatenation of two strings, basically using type conversion between bytes and strings to implement string concatenation:

contract EzDemo {
    function strConcat(string _a, string _b) internal returns (string){
        bytes memory _ba = bytes(_a);
        bytes memory _bb = bytes(_b);
        string memory ret = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
        bytes memory bret = bytes(ret);
        uint k = 0;
        for (uint i = 0; i < _ba.length; i++)bret[k++] = _ba[i];
        for (i = 0; i < _bb.length; i++) bret[k++] = _bb[i];
        return string(ret);
   }  
}

The above code can easily be extended to concatenate multiple strings.

Use third-party libraries

Fortunately, someone wrote a library that saves us some effort:

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());
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324896547&siteId=291194637