<分区>
我想制作一个函数来计算两个字符串中公共(public)段的长度(从头开始)。例如:
foo:="Makan"
bar:="Makon"
结果应该是 3。
foo:="Indah"
bar:="Ihkasyandehlo"
结果应该是1。
标签 string go comparator
<分区>
我想制作一个函数来计算两个字符串中公共(public)段的长度(从头开始)。例如:
foo:="Makan"
bar:="Makon"
结果应该是 3。
foo:="Indah"
bar:="Ihkasyandehlo"
结果应该是1。
最佳答案
不清楚您在问什么,因为您将测试用例限制为 ASCII 字符。
我添加了一个 Unicode 测试用例,并且包含了字节、 rune 或两者的答案。
package main
import (
"fmt"
"unicode/utf8"
)
func commonBytes(s, t string) (bytes int) {
if len(s) > len(t) {
s, t = t, s
}
i := 0
for ; i < len(s); i++ {
if s[i] != t[i] {
break
}
}
return i
}
func commonRunes(s, t string) (runes int) {
if len(s) > len(t) {
s, t = t, s
}
i := 0
for ; i < len(s); i++ {
if s[i] != t[i] {
break
}
}
return utf8.RuneCountInString(s[:i])
}
func commonBytesRunes(s, t string) (bytes, runes int) {
if len(s) > len(t) {
s, t = t, s
}
i := 0
for ; i < len(s); i++ {
if s[i] != t[i] {
break
}
}
return i, utf8.RuneCountInString(s[:i])
}
func main() {
Tests := []struct {
word1, word2 string
}{
{"Makan", "Makon"},
{"Indah", "Ihkasyandehlo"},
{"日本語", "日本語"},
}
for _, test := range Tests {
fmt.Println("Words: ", test.word1, test.word2)
fmt.Println("Bytes: ", commonBytes(test.word1, test.word2))
fmt.Println("Runes: ", commonRunes(test.word1, test.word2))
fmt.Print("Bytes & Runes: ")
fmt.Println(commonBytesRunes(test.word1, test.word2))
}
}
输出:
Words: Makan Makon Bytes: 3 Runes: 3 Bytes & Runes: 3 3 Words: Indah Ihkasyandehlo Bytes: 1 Runes: 1 Bytes & Runes: 1 1 Words: 日本語 日本語 Bytes: 9 Runes: 3 Bytes & Runes: 9 3
关于string - 如何比较golang中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27076044/