输入输出
abc abc___
a a___
abcdeabcde_
尝试
package main
import "fmt"
import "unicode/utf8"
func main() {
input := "abc"
if utf8.RuneCountInString(input) == 1 {
fmt.Println(input + "_____")
} else if utf8.RuneCountInString(input) == 2 {
fmt.Println(input + "____")
} else if utf8.RuneCountInString(input) == 3 {
fmt.Println(input + "___")
} else if utf8.RuneCountInString(input) == 4 {
fmt.Println(input + "__")
} else if utf8.RuneCountInString(input) == 5 {
fmt.Println(input + "_")
} else {
fmt.Println(input)
}
}
返回
abc___
讨论
虽然代码创建了预期的输出,但它看起来非常冗长和曲折。
问题
有没有简洁的方法?
最佳答案
strings包有一个Repeat
函数,所以像
input += strings.Repeat("_", desiredLen - utf8.RuneCountInString(input))
会更简单。您可能应该首先检查 desiredLen
是否小于输入长度。
关于string - 在 Golang 中达到定义的最大长度之前,如何将跟随者字符连接到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35011902/