代码之家  ›  专栏  ›  技术社区  ›  Alec Gorge

简单但混乱的Ruby字符串操作

  •  0
  • Alec Gorge  · 技术社区  · 16 年前

    我正在尝试将一小部分Ruby转换为PHP,目前为止我已经取得了成功,除了这一行:

    string = string[16,string.length-16]
    

    我在PHP中尝试了以下两种方法:

    $string = substr($string, 16, strlen($string) - 16);
    // and
    $string = substr($string, 16, strlen($string) - 32);
    

    但问题是我不知道这是怎么回事 string[#,#] 语法确实如此。我见过 string[#..#] 前后 string[#] ,但从来没有 .

    4 回复  |  直到 16 年前
        1
  •  3
  •   sepp2k    16 年前

    string[x,y] 是一个子字符串,从索引x开始,长度为y个字符(或1.8字节)(与 string[x..y] 从索引x开始,在索引y停止)。

        2
  •  3
  •   Adam Kiss    16 年前

    在我看来 $string = substr($string, 16, strlen($string) - 16);

    哦,还有更多关于ruby中字符串的内容: http://ruby-doc.org/core/classes/String.html#M000771

        3
  •  2
  •   Dan Rosenstark    16 年前

    >> "123456789"[3,2]
    => "45"
    

    这样你就能看到发生了什么。不管怎样,医生 are here

    str.index(substring [, offset]) => fixnum or nil
    str.index(fixnum [, offset]) => fixnum or nil
    str.index(regexp [, offset]) => fixnum or nil
    Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
    
       "hello".index('e')             #=> 1
       "hello".index('lo')            #=> 3
       "hello".index('a')             #=> nil
       "hello".index(101)             #=> 1
       "hello".index(/[aeiou]/, -3)   #=> 4
    
        4
  •  1
  •   gbarry    16 年前

    从你的回答和评论来看,我觉得你的错误在别处。也许$string是空的。通过打印出所有“明显”的东西来测试你的假设。字符串、strlen()的结果等。此外,前一行上的错误(例如未终止的if())可能会产生意外的结果。

    推荐文章