区块链学堂(22):String 数组类型

我不是女神ヾ 2022-06-02 05:36 275阅读 0赞

String类型的官方定义

String literals are written with either double or single-quotes (“foo” or ‘bar’). They do not imply trailing zeroes as in C; “foo”` represents three bytes not four. As with integer literals, their type can vary, but they are implicitly convertible to bytes1, …, bytes32, if they fit, to bytes and to string.

String literals support escape characters, such as \n, \xNN and \uNNNN. \xNN takes a hex value and inserts the appropriate byte, while \uNNNN takes a Unicode codepoint and inserts an UTF-8 sequence. 引用自here

String数组类型定义

  1. string[] strArr

String数组的增删改查

  • Step 1: 首先撰写一个String数组的contract和构造函数

    1. pragma solidity 0.4.10;
    2. contract Demo {
    3. string[] public strArr;
    4. function Demo() {
    5. strArr.push("init");
    6. }
    7. }
  • Step 2: 添加一个Add function

    1. function Add(string str) {
    2. strArr.push(str);
    3. }
  • Step 3: 添加一个Update function

    1. function Update(uint index, string str) {
    2. if (index > strArr.length-1) throw;
    3. strArr[index] = str;
    4. }

    大家注意一下,如果index>strArr.length-1, 此时应抛出异常

  • Step 4: 添加一个ValueOf function

    1. function ValueOf(uint index) returns (string str){
    2. if (index > strArr.length-1) throw;
    3. return strArr[index];
    4. }
  • Step 5: 添加一个DeleteAt function

    function DeleteAt(uint index) {

    1. uint len = strArr.length;
    2. if (index > len-1) throw;
    3. for (uint i = index; i<len-1; i++) {
    4. strArr[i] = strArr[i+1];
    5. }
    6. delete strArr[len-1];
    7. strArr.length--;
    8. }

原文:http://www.ethchinese.com/?p=1022

QQ群:559649971 (区块链学堂粉丝群)
个人微信:steven_k_colin

stevenkcolin.jpg

获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网

ethchinese.jpg

发表评论

表情:
评论列表 (有 0 条评论,275人围观)

还没有评论,来说两句吧...

相关阅读