英文:
How to concatenate follower characters to a string until a defined maximum length has been reached in Golang?
问题
package main
import (
"fmt"
"strings"
)
func main() {
input := "abc"
fmt.Println(strings.ReplaceAll(input, "", "_"))
}
输出:
abc___
讨论:
这段代码使用了 strings.ReplaceAll
函数来将空字符串替换为下划线。这种方法更简洁,不需要使用条件语句。
问题:
有更简洁的方法吗?
英文:
<kbd>Input</kbd><kbd>Output</kbd><br/>
<kbd>abc </kbd><kbd>abc___</kbd><br/>
<kbd>a </kbd><kbd>a___ </kbd><br/>
<kbd>abcde</kbd><kbd>abcde_</kbd><br/>
Attempt
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)
}
}
returns
abc___
Discussion
Although the code is creating the expected output, it looks very verbose and devious.
Question
Is there a concise way?
答案1
得分: 5
strings
包中有一个Repeat
函数,所以可以像下面这样使用:
input += strings.Repeat("_", desiredLen - utf8.RuneCountInString(input))
这样会更简单。在此之前,你应该先检查desiredLen
是否小于输入字符串的长度。
英文:
The strings package has a Repeat
function, so something like
input += strings.Repeat("_", desiredLen - utf8.RuneCountInString(input))
would be simpler. You should probably check that desiredLen
is smaller than inpult length first.
答案2
得分: 5
你也可以高效地完成这个任务,而不需要使用循环和"外部"函数调用,只需通过切片一个预先准备好的"最大填充"(将所需的填充切片并简单地添加到输入中)来实现:
const max = "______"
func pad(s string) string {
if i := utf8.RuneCountInString(s); i < len(max) {
s += max[i:]
}
return s
}
使用它:
fmt.Println(pad("abc"))
fmt.Println(pad("a"))
fmt.Println(pad("abcde"))
输出结果(在Go Playground上尝试):
abc___
a_____
abcde_
注意:
len(max)
是一个常量(因为max
是一个常量):规范:长度和容量
如果
s
是一个字符串常量,表达式len(s)
是常量。
切片一个字符串是高效的:
这种类似切片的字符串设计的一个重要结果是,创建子字符串非常高效。只需要创建一个两字节的字符串头部。由于字符串是只读的,原始字符串和切片操作产生的字符串可以安全地共享同一个数组。
英文:
You can also do this efficiently without loops and "external" function calls, by slicing a prepared "max padding" (slice out the required padding and simply add it to the input):
const max = "______"
func pad(s string) string {
if i := utf8.RuneCountInString(s); i < len(max) {
s += max[i:]
}
return s
}
Using it:
fmt.Println(pad("abc"))
fmt.Println(pad("a"))
fmt.Println(pad("abcde"))
Output (try it on the Go Playground):
abc___
a_____
abcde_
Notes:
len(max)
is a constant (because max
is a constant): Spec: Length and capacity:
> The expression len(s)
is constant if s
is a string constant.
Slicing a string
is efficient:
> An important consequence of this slice-like design for strings is that creating a substring is very efficient. All that needs to happen is the creation of a two-word string header. Since the string is read-only, the original string and the string resulting from the slice operation can share the same array safely.
答案3
得分: 0
你可以在循环中使用input += "_"
,但这样会分配不必要的字符串。下面是一个不会分配多余字符串的版本:
const limit = 6
func f(s string) string {
if len(s) >= limit {
return s
}
b := make([]byte, limit)
copy(b, s)
for i := len(s); i < limit; i++ {
b[i] = '_'
}
return string(b)
}
Playground: http://play.golang.org/p/B_Wx1449QM.
英文:
You could just do input += "_"
in a cycle, but that would allocate unnecessary strings. Here is a version that doesn't allocate more than it needs:
const limit = 6
func f(s string) string {
if len(s) >= limit {
return s
}
b := make([]byte, limit)
copy(b, s)
for i := len(s); i < limit; i++ {
b[i] = '_'
}
return string(b)
}
Playground: http://play.golang.org/p/B_Wx1449QM.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论