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

2.2 去除字符串特别字符

时间:2018-03-21 23:22:07      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:ttl   turn   fst   word   AC   must   pil   equal   ring   

遍历带空格的字符串

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 去除字符串特别字符

标签:ttl   turn   fst   word   AC   must   pil   equal   ring   

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

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