如何在Golang中将跟随者字符连接到字符串中,直到达到定义的最大长度?

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

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&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>abc___</kbd><br/>
<kbd>a&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>a___&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>
<kbd>abcde</kbd><kbd>abcde_</kbd><br/>

Attempt

package main

import &quot;fmt&quot;
import &quot;unicode/utf8&quot;

func main() {
	input := &quot;abc&quot;

	if utf8.RuneCountInString(input) == 1 {
		fmt.Println(input + &quot;_____&quot;)
	} else if utf8.RuneCountInString(input) == 2 {
		fmt.Println(input + &quot;____&quot;)
	} else if utf8.RuneCountInString(input) == 3 {
		fmt.Println(input + &quot;___&quot;)
	} else if utf8.RuneCountInString(input) == 4 {
		fmt.Println(input + &quot;__&quot;)
	} else if utf8.RuneCountInString(input) == 5 {
		fmt.Println(input + &quot;_&quot;)
	} 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(&quot;_&quot;, 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 = &quot;______&quot;

func pad(s string) string {
	if i := utf8.RuneCountInString(s); i &lt; len(max) {
		s += max[i:]
	}
	return s
}

Using it:

fmt.Println(pad(&quot;abc&quot;))
fmt.Println(pad(&quot;a&quot;))
fmt.Println(pad(&quot;abcde&quot;))

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 += &quot;_&quot; 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) &gt;= limit {
		return s
	}
	b := make([]byte, limit)
	copy(b, s)
	for i := len(s); i &lt; limit; i++ {
		b[i] = &#39;_&#39;
	}
	return string(b)
}

Playground: http://play.golang.org/p/B_Wx1449QM.

huangapple
  • 本文由 发表于 2016年1月26日 18:39:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/35011902.html
匿名

发表评论

匿名网友

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

确定