string - 如何比较golang中的字符串?

标签 string go comparator

<分区>

我想制作一个函数来计算两个字符串中公共(public)段的长度(从头开始)。例如:

foo:="Makan"
bar:="Makon"

结果应该是 3。

foo:="Indah"
bar:="Ihkasyandehlo"

结果应该是1。

最佳答案

不清楚您在问什么,因为您将测试用例限制为 ASCII 字符。
我添加了一个 Unicode 测试用例,并且包含了字节、 rune 或两者的答案。

play.golang.org :

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/

相关文章:

arrays - 在另一个用户中插入 ObjectId - Parse 和 Swift

python - 从 Python 调用 Go

java - Java中的2个比较器类

java - 扩展 java 比较器以比较实现它比较的接口(interface)的特定类

java - java中使用优先级队列对元素进行排序

Java: Misspell reporter using regex (如何解析拼写错误)

c++ - 字符串复制构造函数的段错误

javascript - 创建一个接受字符串并将重复值分组的函数

GO:从 SQL 查询返回 map

go - 如何将连接参数 db 传递给 main.go?