zoukankan      html  css  js  c++  java
  • 2.11 whitespace 去掉空格

    
    package main
    
    import (
    	"fmt"
    	"math"
    	"regexp"
    	"strconv"
    	"strings"
    )
    
    func main() {
    
    	stringToTrim := "		
       Go 	is	 Awesome 		"
    	trimResult := strings.TrimSpace(stringToTrim)
    	fmt.Println(trimResult)
    
    	stringWithSpaces := "		
       Go 	is
     Awesome 		"
    	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
    
    */
    
    
  • 相关阅读:
    centos安装libreoffice
    世界,你好!
    4.闭包函数
    3.回调函数
    1内存地址
    2.函数递归
    1.字典
    nonlocal可以修改外层函数变量
    单例模式(Singleton)示例源码
    大家来说说自己的WEB开发工具好吗?
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8620710.html
Copyright © 2011-2022 走看看