Solidity programming language: strings, arrays

String

The definition of a string can be either single or double quotes. Here mainly talk about the common operations of string, not very convenient in solidity.

pragma solidity >=0.4.0 <0.6.0; //import "github.com/Arachnid/solidity-stringutils/strings.sol"; contract EgString { string name = 'buff'; string addr = "beijing"; unction getAddrLength()public returns(uint){ return bytes(addr).length;//获取字符串} function concatenateWithAbi ()public returns(string memory){ return string(abi.encodePacked(name, addr)); } /*function concatenateWithGit() public returns(string memory){ return name.toSlice().concat(addr.toSlice()); }*/ function compare1() public returns(bool){ return keccak256(bytes(name)) == keccak256(bytes(addr)); } function compare2() public returns (bool){ for (uint i = 0; i < bytes(name).length; i ++) { if(bytes(name)[i] != bytes(addr)[i]) { return false; } } } /* // parseInt(parseFloat*10^_b) function parseInt(string memory _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string memory) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); }*/ }

length

String length acquisition needs to convert string to bytes, and then use the length property of bytes to get the length.

splice

  1. String splicing, the method given on the official website is to use the abi.encodePacked method.
  2. You can also write a method yourself, the idea is to convert the string into bytes, then merge the bytes into a large byte, and finally convert the resulting bytes into strings. The bytes and string conversion methods are bytes(string), string(bytes), and the code is not written here.
  3. Someone on the Internet uses a toolkit on git , but I have not compiled it myself, and I will check the reason later. Browse the code below and learn. Comparing Solidity also does not support string comparison, you need to implement it yourself. Here are two ways (not including other toolkit methods). Of course, for performance requirements and gas consumption, you can first compare the length of the string. Then compare the content. This article is written well, and there are gas consumption test statistics.
  4. Compare whether the hashes of two-character strings are equal.
  5. Comparing each character int conversion one by one Solidity also does not support the conversion of string and int. Here you can directly view the tool class oraclize . The conversion idea is to convert the string first into a bytes type, and then traverse it one by one to perform numerical summation.

Array

In solidity, arrays are divided into fixed-length arrays and non-fixed-length arrays. As the name implies, the length of the array after the name can be changed.

Fixed length array

pragma solidity >=0.4.0 <0.6.0; contract EgFixedArray { uint[5] arr1 = [1,2,3,4,5]; //uint[5] arr1 = []; //uint[5] arr2 = new uint[](5); function modifyLen()public{ // arr1.length = 2;编译失败} function modifyElement()public { arr1[1] = 3; } function pushToArray() public{ // arr1.push(1);编译失败} }

  1. Fixed-length arrays must initialize elements and cannot be created with new.
  2. The length attribute of a fixed-length array cannot be modified, otherwise a compile error will be reported.
  3. Fixed-length array elements are modifiable, but need to be indexed.
  4. Fixed-length arrays cannot use the push method, the compilation cannot pass, and the length array is not fixed.

pragma solidity >=0.4.0 <0.6.0; contract EgUnFixedArray { //uint[] arr1 = [1,2,3,4,5]; uint[] arr1 = new uint[](5); function modifyLen()public{ arr1.length = 2; } function modifyElement()public { arr1[1] = 3; } function pushToArray() public { arr1.push(1); } }

  1. Unfixed length array, can be named by new, the default value of the element is the default value of the array type.
  2. The length can be modified. If the modified length is smaller than the original, the array element is removed from the back.
  3. Elements can be modified.
  4. You can use the push method. After the push, the data length is increased by one. The push method returns the length of the array to modify the array.

function modifyMemoryArr() public returns(uint){ uint8[5] memory arr2 = [1,2,3,4,5]; // arr2.push(6); // arr2.length = 6; return arr2.length; }

  1. The memory-qualified array must specify the length of the array.
  2. Memory-qualified arrays cannot use the push method.
  3. Memory modified arrays cannot modify the length property.

function inputArr(uint[5] arr) public{ // arr.length = 6; // arr.push(6); }

For method parameters that are array type parameters, the default is also memory modified, so you can't use the length property and the push method.

function assignment() public{ // uint[] memory x = [uint(1), 3, 4]; // uint[] x = [uint(1), 3, 4]; uint[3] memory x = [uint(1), 3, 4]; uint[] memory x1 = new uint[](3); }

  1. Fixed-length arrays cannot be assigned to an array of unfixed lengths decorated with memory.
  2. Unfixed length arrays cannot be assigned using array literals.

function testReturn1() public returns(uint[3] memory){ uint[3] memory u1 = [uint(1),2,3]; return u1; } function testReturn2() public returns(uint[] memory){ uint[] memory u2 = new uint[](5); return u2; }

Remarks: I have seen on the Internet that the return value cannot use an unfixed length array. I can use the solidity version of 0.5.2 to check it. It may be that the old version does not work.

Author: thank HPB Wallet team finishing feeds.

Wang Xiaoming blog http://wangxiaoming.com/

Wang Xiaoming: Founder of HPB core chain, Babbitt columnist. More than ten years of experience in financial big data and blockchain technology development, he has participated in the creation of UnionPay big data. The main creative blockchain teaching video program "Ming Shuo" more than 30 issues, compiled the "Ethernet official website document Chinese version", and as the main author wrote the "blockchain development guide", in the Chinese blockchain community with ID "blue lotus "famous.

We will continue to update Blocking; if you have any questions or suggestions, please contact us!

Share:

Was this article helpful?

93 out of 132 found this helpful

Discover more

Blockchain

Bella Fang: The exchange is at the top of the food chain. How can small and medium-sized projects seize this channel?

On the afternoon of the 9th, at the 2nd Global Blockchain Summit·Wuzhen site hosted by Babbitt, Bella Fang, foun...

Opinion

Research on the major wallet risks of Binance, KuCoin, and Jump: Are assets stored in large institutions 100% safe?

Undoubtedly, mainstream exchanges and institutions have invested a significant amount of funds and manpower in networ...

Blockchain

Starting to decentralize the game platform: Is it a good day to break the monopoly?

On May 31 , Xiao Xiao invited the founding partner of Xingyao Capital, Liu Jiang, founder of Xingheng Education, Chen...

Market

The ultimate way out of cryptocurrency exchanges: decentralization (below)

The full text is brief: Alicoin|Exclusive view With the endless stream of asset security cases such as hacking and se...

Opinion

Forbes Binance's Golden Touch, how did they turn failed ICO tokens into unexpected fortunes worth billions of dollars?

In this article, we will see a detailed analysis by Forbes of BNB's initial token issuance and the subsequent years' ...

Blockchain

Interview with Justin Sun: Web3 Yu'ebao stUSDT, Tron's Ambition to Connect DeFi and TradFi

stUSDT allows users to access low-risk and stable investment opportunities in national bonds, and supports flexible w...