zoukankan      html  css  js  c++  java
  • 2.2 去除字符串特别字符

    遍历带空格的字符串

    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
    ", 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
    ", 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
    ", 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
    ", idx, word)
    	}
    
    }
    
    /*
    Word 0 is: Mary
    Word 1 is: had
    Word 2 is: a
    Word 3 is: little
    Word 4 is: lamb
    
    */
    
    
  • 相关阅读:
    python redis操作
    subprocess模块的使用
    tcpcopy 流量复制工具
    Python名称空间与闭包
    python 偏函数
    Python面向对象的特点
    vsftpd 安装及使用虚拟用户配置
    shell 并发脚本
    Centos7 搭建LVS DR模式 + Keepalive + NFS
    python pip 升级
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8620288.html
Copyright © 2011-2022 走看看