在Rebol中计算线路的最快/最有效的方法是什么?

时间:2013-02-08 05:02:02

标签: string performance newline rebol

给定字符串string,在其中计算行的最快/最有效的方法是什么?将接受任何风格的Rebol的最佳答案。我一直在假设parse [some [thru]]组合是遍历字符串的最快方法,但后来我不知道这一点,因此转向SO:

count-lines: func [string [string!] /local count][
    parse/all string [
        (count: 1) some [thru newline (count: count + 1)]
    ]
    count
]

或者:

count-lines: func [string [string!] /local count][
    count: 0
    until [
        count: count + 1
        not string: find/tail string newline
    ]
    count
]

柜台怎么样?效率如何重复?

count-lines: func [string [string!]][
    repeat count length? string [
        unless string: find/tail string newline [
            break/return count
        ]
    ]
]

更新:行数采用文本编辑器原则:

Empty TextMate Document

空文档的行数仍为1。所以:

>> count-lines ""
== 1
>> count-lines "^/"
== 2

9 个答案:

答案 0 :(得分:4)

count-lines: func [
    str
    /local sort-str ][
sort-str: sort join str "^/"
1 + subtract index? find/last sort-str "^/" index? find sort-str "^/"
]

答案 1 :(得分:4)

增强的PARSE版本,如BrianH所建议的那样:

i: 1 ; add one as TextMate
parse text [any [thru newline (++ i)]]
print i

答案 2 :(得分:3)

这是我能想到的最简单的非parse版本:

count-lines: function [text [string!]] [
    i: 1
    find-all text newline [++ i]
    i
]

它使用来自更新版Rebol的function++,以及来自R3或R2 / Forward的find-all。您可以查看find-all的来源并内联您找到并优化的内容,但这样的情况正是我们为find-all编写的内容,为什么不使用它呢?

答案 3 :(得分:2)

这对我来说是最好的:

temp: read/lines %mytext.txt
length? temp

答案 4 :(得分:2)

删除 - 每个都可以快速,因为它是原生的

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

或作为一种功能

>> f: func [s] [print [(length? s) - (length? remove-each v s [v = #"^/"])]]
>> f "1^/2^/3"
== 2

答案 5 :(得分:2)

为什么没有人带着我想知道的最简单的解决方案:)

t: "abc^/de^/f^/ghi"
i: 0 until [i: i + 1 not t: find/tail t newline] i
== 4

不确定性能,但我认为它非常快,因为UNTIL和FIND是本地人。 也可以使用WHILE。

i: 1 while [t: find/tail t newline] [i: i + 1] i
== 4

只需要检查空字符串。如果它是一个函数,则参数系列需要被HEADed。

答案 6 :(得分:2)

不是最有效的,但可能是最快的解决方案之一(无论如何,如果运行基准测试,我想看看这个解决方案的表现如何):

>> s: "1^/2^/ ^/^/3"
>> (length? s) - length? trim/with copy s newline
== 4

答案 7 :(得分:1)

不了解性能和最后一行规则(r3)。

>> length? parse "1^/2^/3" "^/"
== 3

答案 8 :(得分:-1)

呵呵hehehe读/行长?温度是一件好事我虽然读/行 - > foreach lines temps [count:count + 1]

另一种方法是做

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? 

我喜欢在rebol中编码它很有趣

编辑我没有阅读整篇文章所以我的解决方案已经以不同的方式提出......

好的修改我发布已经发布的解决方案的罪我会带来洞察力评论该解决方案的意外行为。不计算多个链式回车(使用rebol3 linux ...)

>> a: "line1 ^M line2 ^M line3 ^M^M"
== "line1 ^M line2 ^M line3 ^M^M"

>> length? parse a newline 
== 3
相关问题