dpjtn48868 2017-11-11 16:24
浏览 59
已采纳

查找行数最快的方法?

What I'm using right now:

numlines := strings.Count(editor.Text(), "
")
fmt.Print(strconv.Itoa(numlines))
message.SetText(strconv.Itoa(numlines))

This is run whenever a text box is updated. What the most go-like way to do this?

  • 写回答

2条回答 默认 最新

  • dqo88037 2017-11-11 16:42
    关注

    That is perfectly fine. But don't forget that if the last character is not a newline character, you have to add 1 to the number of occurrences, as that will be the number of lines (the last line may not end with a newline).

    What we might think is that since the substring you're counting is only a single character (a single rune), we could create a custom solution counting only the occurrence of this single character (instead of counting substrings). It may look like this:

    func countRune(s string, r rune) int {
        count := 0
        for _, c := range s {
            if c == r {
                count++
            }
        }
        return count
    }
    

    (A for range on a string value iterates over its runes.)

    And testing it (try it on the Go Playground):

    fmt.Println(countRune("asdf
    asdf
    asdf
    ", '
    ')) // Prints 3
    

    In practice this won't be faster counting newline characters, as that is a single byte in UTF-8 encoding, and strings.Count() is already optimized for counting substrings where the length of the substring is 1:

    // Count counts the number of non-overlapping instances of substr in s.
    // If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
    func Count(s, substr string) int {
        if len(substr) == 1 && cpu.X86.HasPOPCNT {
            return countByte(s, byte(substr[0]))
        }
        return countGeneric(s, substr)
    }
    
    func countByte(s string, c byte) int // ../runtime/asm_amd64.s
    

    What could improve the performance of this operation (counting lines) is if you would have access to the "internal" byte or rune array of the editor, so you would not have to call its Text() method, which creates and returns a copy of its content.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集