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

2.12 指定缩进

时间:2018-03-22 00:25:54      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:inpu   main   pack   class   ==   code   iss   ase   fun   


package main

import (
    "fmt"
    "strconv"
    "strings"
    "unicode"
)

func main() {

    text := "Hi! Go is awesome."
    text = Indent(text, 6)
    fmt.Println(text)

    text = Unindent(text, 3)
    fmt.Println(text)

    text = Unindent(text, 10)
    fmt.Println(text)

    text = IndentByRune(text, 10, ‘.‘)
    fmt.Println(text)

}

// Indent indenting the input by given indent and rune
func IndentByRune(input string, indent int, r rune) string {
    return strings.Repeat(string(r), indent) + input
}

// Indent indenting the input by given indent
func Indent(input string, indent int) string {
    padding := indent + len(input)
    return fmt.Sprintf("% "+strconv.Itoa(padding)+"s", input)
}

// Unindent unindenting the input string. In case the
// input is indented by less than "indent" spaces
// the min of this both is removed.
func Unindent(input string, indent int) string {

    count := 0
    for _, val := range input {
        if unicode.IsSpace(val) {
            count++
        }
        if count == indent || !unicode.IsSpace(val) {
            break
        }
    }

    return input[count:]
}

/*
      Hi! Go is awesome.
   Hi! Go is awesome.
Hi! Go is awesome.
..........Hi! Go is awesome.

*/

2.12 指定缩进

标签:inpu   main   pack   class   ==   code   iss   ase   fun   

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

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