码迷,mamicode.com
首页 > 其他好文 > 详细

2.11 whitespace 去掉空格

时间:2018-03-22 00:24:57      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:switch   ceil   ace   ring   compile   AC   out   mpi   itoa   


package main

import (
    "fmt"
    "math"
    "regexp"
    "strconv"
    "strings"
)

func main() {

    stringToTrim := "\t\t\n   Go \tis\t Awesome \t\t"
    trimResult := strings.TrimSpace(stringToTrim)
    fmt.Println(trimResult)

    stringWithSpaces := "\t\t\n   Go \tis\n Awesome \t\t"
    r := regexp.MustCompile("\\s+")
    replace := r.ReplaceAllString(stringWithSpaces, " ")
    fmt.Println(replace)

    needSpace := "need space"
    fmt.Println(pad(needSpace, 14, "CENTER"))
    fmt.Println(pad(needSpace, 14, "LEFT"))
}

func pad(input string, padLen int, align string) string {
    inputLen := len(input)

    if inputLen >= padLen {
        return input
    }

    repeat := padLen - inputLen
    var output string
    switch align {
    case "RIGHT":
        output = fmt.Sprintf("% "+strconv.Itoa(-padLen)+"s", input)
    case "LEFT":
        output = fmt.Sprintf("% "+strconv.Itoa(padLen)+"s", input)
    case "CENTER":
        bothRepeat := float64(repeat) / float64(2)
        left := int(math.Floor(bothRepeat)) + inputLen
        right := int(math.Ceil(bothRepeat))
        output = fmt.Sprintf("% "+strconv.Itoa(left)+"s% "+strconv.Itoa(right)+"s", input, "")
    }
    return output
}

/*
Go  is   Awesome
 Go is Awesome
  need space
    need space

*/

2.11 whitespace 去掉空格

标签:switch   ceil   ace   ring   compile   AC   out   mpi   itoa   

原文地址:https://www.cnblogs.com/zrdpy/p/8620710.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!