2016-01-26 11 views
3

输入输出
ABC        abc___
一个               a___        
ABCDEabcde_
如何将跟随者字符连接到一个字符串,直到在Golang中达到定义的最大长度为止?

尝试

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___ 

讨论

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

问题

有一个简洁的方式?

回答

5

strings封装具有Repeat功能,所以像

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

会更简单。您应该先检查desiredLen小于inpult长度。

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) 
} 

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

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

表达len(s)constant如果s是字符串常量。

切片一个stringefficient

字符串这片状设计的一个重要后果是,创建一个子是非常有效的。所有需要发生的是创建一个双字串标头。由于字符串是只读的,原始字符串和切片操作产生的字符串可以安全地共享相同的数组。

相关问题