len()函数没有给我正确的结果。

huangapple go评论80阅读模式
英文:

len() is not giving me the right result

问题

s1和s2在连接字符串后应该具有相同的长度,长度应该是相等的。

package main
import . "fmt"

func stamp(s1 string, s2 string) (result string){
  if len(s1) > len(s2) {
    for i := 0; i < (len(s1) - len(s2)); i++{
      s2 += "-"
    }
  } else if len(s1) < len(s2) {
    for i := 0; i < (len(s2) - len(s1)); i++ {
      s1 += "-"
    }
  }

  for i := 0; i < len(s2); i++ {
    result += string(s1[i]) + string(s2[i])
  }
  return
}

func main(){
  var s1, s2 string
  Print("插入两个单词:")
  Scan(&s1, &s2)
  Println(stamp(s1,s2))
}

尝试将s1设置为"esame",s2设置为"go",stamp得到的结果是egsoa-m-,应该是egsoa-m-e-。

尝试将s2设置为"go",s1设置为"esame",stamp得到的结果是:

panic: runtime error: index out of range [4] with length 4

goroutine 1 [running]:
main.stamp(...)
	/home/Usr/Info/es19.go:16
main.main()
	/home/Usr/Info/es19.go:25 +0x2ac
exit status 2
英文:

The lenght of s1 and s2 should be the same after concatenating "-" to the string to have the same lenght

package main
import . &quot;fmt&quot;

func stamp(s1 string, s2 string) (result string){
  if len(s1) &gt; len(s2) {
    for i := 0; i &lt; (len(s1) - len(s2)); i++{
      s2 += &quot;-&quot;
    }
  } else if len(s1) &lt; len(s2) {
    for i := 0; i &lt; (len(s2) - len(s1)); i++ {
      s1 += &quot;-&quot;
    }
  }

  for i := 0; i &lt; len(s2); i++ {
    result += string(s1[i]) + string(s2[i])
  }
  return
}

func main(){
  var s1, s2 string
  Print(&quot;Insert 2 words: &quot;)
  Scan(&amp;s1, &amp;s2)
  Println(stamp(s1,s2))
}

Tried s1 as "esame"
s2 as "go"
stamp got egsoa-m- // should be egsoa-m-e-

Tried s2 as "go"
s1 as "esame"
stamp got

panic: runtime error: index out of range [4] with length 4

goroutine 1 [running]:
main.stamp(...)
	/home/Usr/Info/es19.go:16
main.main()
	/home/Usr/Info/es19.go:25 +0x2ac
exit status 2

答案1

得分: 1

这是一个常见的编程陷阱,即在访问数组/切片时不应该修改它。在这种情况下,你试图在遍历过程中向s1/s2追加“-”,而for循环依赖于len(s1)和len(s2)的差值。假设s1和s2的初始长度分别为2和5,差值为3,在第一轮之后,s1的长度变为3,i变为1,差值变为2,循环继续。但是,在第二轮之后,s1的长度变为4,i变为2,差值现在为1,所以循环在这里结束。你可能期望有3轮循环,但实际上只有2轮。

更重要的是,Go语言的len函数是动态调用的。因此,解决方案是在for循环之前添加一行代码来保存初始长度差值,即下面的sub行。我相信这会得到你想要的结果。

        if len(s1) > len(s2) {
                sub := len(s1) - len(s2)
                for i := 0; i < sub; i++ {
                        s2 += "-"
                }
        } else if len(s1) < len(s2) {
                sub := len(s2) - len(s1)
                for i := 0; i < sub; i++ {
                        s1 += "-"
                }
        }
英文:

This is a common programing pitfall which is that you shouldn't modify an/a array/slice while visiting it. In this case, you try to append '-' to s1/s2 while the for-loop depends on the subtraction of len(s1) and len(s2). Let's assume the initial length of s1 and s2 to be 2 and 5, the delta is 3, after the first round, length of s1 becomes 3 and the i becomes 1, the delta is 2, the loop continues. But, after the second round, length of s1 becomes 4 and i becomes 2, the delta is now 1, so the loop ends here. You may expect 3 rounds while it turns out to be 2.

More to learn is that Go's len function is dynamic called. So the solution is to add one line above the for-loop to save the initial length delta, which is the sub line below. I believe it will give what you want.

        if len(s1) &gt; len(s2) {
                sub := len(s1) - len(s2)
                for i := 0; i &lt; sub; i++ {
                        s2 += &quot;-&quot;
                }
        } else if len(s1) &lt; len(s2) {
                sub := len(s2) - len(s1)
                for i := 0; i &lt; sub; i++ {
                        s1 += &quot;-&quot;
                }
        }

huangapple
  • 本文由 发表于 2022年11月10日 03:10:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/74380179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定