我现在正在使用的是:
numlines := strings.Count(editor.Text(), "\n")
fmt.Print(strconv.Itoa(numlines))
message.SetText(strconv.Itoa(numlines))
每当更新文本框时,就会运行该命令。最像这样的方式是什么?
最佳答案
很好。但是请不要忘记,如果最后一个字符不是换行符,则必须在出现次数上加1,因为这将是行数(最后一行不能以换行符结尾)。
我们可能会认为,由于您要计数的子字符串仅是一个字符(单个rune
),因此我们可以创建一个自定义解决方案,仅计算此单个字符的出现(而不是对子字符串进行计数)。它可能看起来像这样:
func countRune(s string, r rune) int {
count := 0
for _, c := range s {
if c == r {
count++
}
}
return count
}
(在
for range
值上的string
遍历其rune
。)并进行测试(在Go Playground上尝试):
fmt.Println(countRune("asdf\nasdf\nasdf\n", '\n')) // Prints 3
实际上,这不会更快地计算换行符,因为这是UTF-8编码中的单个
byte
,而且 strings.Count()
已经优化用于计算子字符串长度为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
可以提高此操作(计数行)的性能的是,如果您可以访问编辑器的“内部”字节或 rune 数组,那么就不必调用其
Text()
方法,该方法创建并返回其副本。内容。关于string - 查找行数最快的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47240127/