What's the fastest/most efficient way to count lines in Rebol?

前端 未结 9 871
星月不相逢
星月不相逢 2021-01-02 07:33

Given a string string, what is the fastest/most-efficient way to count lines therein? Will accept best answers for any flavour of Rebol. I\'ve been working unde

相关标签:
9条回答
  • 2021-01-02 07:59

    Enhanced PARSE version, as suggested by BrianH:

    i: 1 ; add one as TextMate
    parse text [any [thru newline (++ i)]]
    print i
    
    0 讨论(0)
  • 2021-01-02 07:59

    Here is the best for me:

    temp: read/lines %mytext.txt
    length? temp
    
    0 讨论(0)
  • 2021-01-02 08:00

    Not the most efficient, but probably one of the fastest solution (anyway if a benchmark is run, I would like to see how this solution performs):

    >> s: "1^/2^/ ^/^/3"
    >> (length? s) - length? trim/with copy s newline
    == 4
    
    0 讨论(0)
  • 2021-01-02 08:08

    hehehe the read/lines length? temp is a great thing I though about read/lines -> foreach lines temps [ count: count + 1]

    another way to do it would be to do

    temp: "line 1 ^M line2 ^M  line3 ^M "
    length? parse temp newline ; that cuts the strings into a block 
    ;of multiple strings that represent each a line [ "line 1" "line2" "line3" ] 
    :then you count how much  strings you have in the block with length? 
    

    I like to code in rebol it is so funny

    Edit I didnt read the whole post so my solution already waas proposed in a different way...

    ok to amend for my sin of posting a already posted solution I will bring insight comment of a unexpected behavior of that solution. Multiple chained carriage returns are not counted (using rebol3 linux ...)

    >> a: "line1 ^M line2 ^M line3 ^M^M"
    == "line1 ^M line2 ^M line3 ^M^M"
    
    >> length? parse a newline 
    == 3
    
    0 讨论(0)
  • 2021-01-02 08:12

    remove-each can be fast as it is native

    s: "1^/2^/3"
    a: length? s
    print a - length? remove-each v s [v = #"^/"]
    ; >> 2
    

    or as a function

    >> f: func [s] [print [(length? s) - (length? remove-each v s [v = #"^/"])]]
    >> f "1^/2^/3"
    == 2
    
    0 讨论(0)
  • 2021-01-02 08:14
    count-lines: func [
        str
        /local sort-str ][
    sort-str: sort join str "^/"
    1 + subtract index? find/last sort-str "^/" index? find sort-str "^/"
    ]
    
    0 讨论(0)
提交回复
热议问题