Ethereum Smart Contract Development Part 5: String Concatenation—Solidity

In the previous article, we implemented a simple smart contract. Whatever string the user enters, the contract returns what it is. At the end of the article, a question is thrown: If we define the Hello string in the contract in advance, how to concatenate the string with the name variable?

Concatenating strings in smart contracts is not an easy task. This article will introduce the string splicing in smart contracts.

try

Let's try to modify the code by using the connectors + and . that are common to most languages:

//pragma关键字:版本申明。
//用来指示编译器将代码编译成特定版本,以免引起兼容性问题
//此处不支持0.4.0之前的编译器,也不支持0.5.0之后的编译器(条件为 ^)
pragma solidity ^0.4.0;

//contract关键字:合约申明
//和Java、PHP中的class类似
//此处是申明一个名为Hello的合约
contract Hello {

    string str="Hello ";

    //public: 函数访问属性(后续文章为详细阐述)
    //returns (string): 定义返回值类型为string
    function say(string name) public returns (string) {
        return str + name;
    }
}

<!--more-->

After running the node deploy.js deployment script, an exception was thrown:

TypeError: Operator + not compatible with types string storage ref and string memory
return str + name;

After we modified it to . and tried to deploy, an exception was also thrown:

TypeError: Member "name" not found or not visible after argument-dependent lookup in string storage ref return str . name;

Note that in smart contracts, ***+*** and . are not connectors. By consulting the Solidity official documentation , we found that the Solidity language does not provide a syntax for string concatenation: Solidity DocumentationIs there any other way to implement the string concatenation function?

The following parts are exclusive benefits for paid users, please click the link to jump to my column to pay for purchase. By reading the following sections, you will learn:

  • Third-party string tool contract: extended processing of strings (finding, splitting, comparing, splicing, etc.)
  • The introduction of third-party contracts in smart contracts
  • String concatenation

My column: Smart contracts Smart contract development QQ group: 753778670

Smart contract development QQ group


There are currently several sets of video courses on blockchain practice (video + source code), if you need it, you can add me on WeChat (kuangwenjie) and send me a private message (paid):

  • "Blockchain" from zero construction of Ethereum (Ethereum) smart contracts to actual projects
  • Development of a decentralized Ebay blockchain project based on Ethereum & IPFS
  • HyperLedger Fabric

Guess you like

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