【发布时间】:2021-11-30 07:25:47
【问题描述】:
请帮我写一个函数,它接受一个字符串和一个数字的输入并将一个缩短的字符串输出到数字+“...”。如果字符串不超过大小(数字),则只输出此字符串,但不带“...”。此外,我们的字符串仅使用单字节字符,并且数字严格大于零。
我的两次尝试:
package main
import (
"fmt"
)
func main() {
var text string
var width int
fmt.Scanf("%s %d",&text,&width)
res := text[:width]
fmt.Println(res+"...")
}
但是这个函数加上“...”即使字符串不超过宽度。
package main
import (
"fmt"
)
var text string
var width int
fmt.Scanf("%s %d",&text,&width)
if width <= 0 {
fmt.Println("")
}
res := ""
count := 0
for _, char := range text {
res += string(char)
count++
if count >= width {
break
}
}
fmt.Println(res+"...")
}
此功能的工作方式相同。
【问题讨论】:
-
最简单的方法是将字符串转换为
[]rune,这样您就可以检查它有多少符文。仅在大于限制时对其进行切片并附加...。
标签: arrays string go substring truncate