【问题标题】:How to concatenate follower characters to a string until a defined maximum length has been reached in Golang?如何将跟随者字符连接到字符串,直到在 Golang 中达到定义的最大长度?
【发布时间】:2016-01-26 10:39:13
【问题描述】:

输入输出
abc    abc___ kbd>
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___

讨论

虽然代码正在创建预期的输出,但它看起来非常冗长和迂回。

问题

有没有简洁的方法?

【问题讨论】:

    标签: string go char string-concatenation maxlength


    【解决方案1】:

    strings 包有一个 Repeat 函数,类似于

    input += strings.Repeat("_", desiredLen - utf8.RuneCountInString(input))
    

    会更简单。您可能应该首先检查desiredLen 是否小于输入长度。

    【讨论】:

      【解决方案2】:

      您也可以在没有循环和“外部”函数调用的情况下有效地执行此操作,方法是切片准备好的“最大填充”(切出所需的填充并简单地将其添加到输入中):

      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 是一个常量):Spec: Length and capacity:

      如果s 是字符串常量,则表达式len(s)constant

      切片stringefficient

      这种类似切片的字符串设计的一个重要结果是创建子字符串非常有效。所需要做的就是创建一个两个字的字符串标题。由于字符串是只读的,所以原始字符串和切片操作得到的字符串可以安全地共享同一个数组。

      【讨论】:

        【解决方案3】:

        您可以只在一个循环中执行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)
        }
        

        游乐场:http://play.golang.org/p/B_Wx1449QM.

        【讨论】:

          猜你喜欢
          • 2021-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-28
          • 1970-01-01
          • 2022-06-17
          • 2013-09-05
          • 2016-04-15
          相关资源
          最近更新 更多