首页 > 其他 > 详细

2.2 去除字符串特别字符

时间:2018-03-21 22:52:04      阅读:181      评论:0      收藏:0      [点我收藏+]

遍历带空格的字符串

package main

import (
    "fmt"
    "strings"
)

const refString = "Mary had a little lamb"

func main() {

    words := strings.Fields(refString)
    for idx, word := range words {
        fmt.Printf("Word %d is: %s\n", idx, word)
    }

}

/*
Word 0 is: Mary
Word 1 is: had
Word 2 is: a
Word 3 is: little
Word 4 is: lamb
*/

指定分割的字符串

package main

import (
    "fmt"
    "strings"
)

const refString = "Mary_had a little_lamb"

func main() {

    words := strings.Split(refString, "_")
    for idx, word := range words {
        fmt.Printf("Word %d is: %s\n", idx, word)
    }

}

/*
Word 0 is: Mary
Word 1 is: had a little
Word 2 is: lamb

*/

去除特别符号

package main

import (
    "fmt"
    "strings"
)

const refString = "Mary*had,a%little_lamb"

func main() {

    // The splitFunc is called for each
    // rune in a string. If the rune
    // equals any of character in a "*%,_"
    // the refString is splitted.
    splitFunc := func(r rune) bool {
        return strings.ContainsRune("*%,_", r)
    }

    words := strings.FieldsFunc(refString, splitFunc)
    for idx, word := range words {
        fmt.Printf("Word %d is: %s\n", idx, word)
    }

}

/*
Word 0 is: Mary
Word 1 is: had
Word 2 is: a
Word 3 is: little
Word 4 is: lamb
*/

正则去掉特别字符串

package main

import (
    "fmt"
    "regexp"
)

const refString = "Mary*had,a%little_lamb"

func main() {

    words := regexp.MustCompile("[*,%_]{1}").Split(refString, -1)
    for idx, word := range words {
        fmt.Printf("Word %d is: %s\n", idx, word)
    }

}

/*
Word 0 is: Mary
Word 1 is: had
Word 2 is: a
Word 3 is: little
Word 4 is: lamb

*/

2.2 去除字符串特别字符

原文:https://www.cnblogs.com/zrdpy/p/8620288.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!