doushenken2833 2014-11-22 09:49 采纳率: 0%
浏览 40

如何在golang中比较字符串? [关闭]

I want to make a function that calculates the length of the common segment (starting from the beginning) in two strings. For example:

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

The result should be 3.

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

The result should be 1.

  • 写回答

3条回答 默认 最新

  • dougan4663 2014-11-22 10:25
    关注

    You mean like this. Please note, this will not handle UTF 8, only ascii.

    package main
    
    import (
        "fmt"
    )
    
    func equal(s1, s2 string) int {
        eq := 0
        if len(s1) > len(s2) {
            s1, s2 = s2, s1
        }
        for key, _ := range s1 {
            if s1[key] == s2[key] {
                eq++
            } else {
                break
            }
        }
        return eq
    }
    
    func main() {
        fmt.Println(equal("buzzfizz", "buzz"))
        fmt.Println(equal("Makan", "Makon"))
        fmt.Println(equal("Indah", "Ihkasyandehlo"))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试