golang字符串指定位数超过截取,不够填充

作者: adm 分类: go 发布时间: 2022-04-18 11:48

方式一:

func StrPad(ending string) string {
	switch {
	case len(ending) <= 9:
		return fmt.Sprintf("%09s", ending)
	case len(ending) > 9:
		return fmt.Sprintf("%.9s",ending[len(ending)-9:])

	default:
		/*should never meet here*/
		return ending
	}
}

方式二:

func StringFormat9(raw string) string {

     switch {
     case len(raw) == 9:
         return raw
     case len(raw) > 9:
         return fmt.Sprintf("%.9s",raw[:9])
     case len(raw) < 9:
         return fmt.Sprintf("%s%s",raw,strings.Repeat("_",9-len(raw)))
     default:
         /*should never meet here*/
         return raw
     }
 }

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!