zoukankan      html  css  js  c++  java
  • Go基础编程实践(一)—— 操作字符串

    修剪空格

    strings包中的TrimSpace函数用于去掉字符串首尾的空格。

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        helloWorld := "	 Hello, World "
        trimHello := strings.TrimSpace(helloWorld)
    
        fmt.Printf("%d %s
    ", len(helloWorld), helloWorld)
        fmt.Printf("%d %s
    ", len(trimHello), trimHello)
    
        // 15    Hello, World 
        // 12 Hello, World
    }
    

    提取子串

    Go字符串的底层是read-only[]byte,所以对切片的任何操作都可以应用到字符串。

    package main
    
    import "fmt"
    
    func main() {
        helloWorld := "Hello, World and Water"
        cutHello := helloWorld[:12]
        fmt.Println(cutHello)
        // Hello, World
    }
    

    替换子串

    strings包的Replace函数可以对字符串中的子串进行替换。

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        helloWorld := "Hello, World. I'm still fine."
        replaceHello := strings.Replace(helloWorld, "fine", "OK", 1)
        fmt.Println(replaceHello)
        // Hello, World. I'm still OK.
    }
    // 注:Replace函数的最后一个参数表示替换子串的个数,为负则全部替换。
    

    转义字符

    字符串中需要出现的特殊字符要用转义字符转义先,例如 需要写成\t

    package main
    
    import "fmt"
    
    func main() {
        helloWorld := "Hello, 	 World."
        escapeHello := "hello, \t World."
        fmt.Println(helloWorld)
        fmt.Println(escapeHello)
        // Hello,    World.
        // Hello, 	 World.
    }
    

    大写字符

    strings包的Title函数用于将每个单词的首字母大写,ToUpper函数则将单词的每个字母都大写。

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        helloWorld := "hello, world. i'm still fine."
        titleHello :=strings.Title(helloWorld)
        upperHello := strings.ToUpper(helloWorld)
        fmt.Println(titleHello)
        fmt.Println(upperHello)
        // Hello, World. I'M Still Fine.
        // HELLO, WORLD. I'M STILL FINE.
    }
    
  • 相关阅读:
    Python-Basis-9th
    Python-Basis-8th
    Python-Basis-7th
    Ubuntu-Basis-4th
    Ubuntu-Basis-3rd
    Ubuntu-Basis-2nd
    Ubuntu-Basis-1st
    疯狂java第五章&&第六章-面向对象
    疯狂java第四章-流程控制与数组
    疯狂java第三章-数据类型和运算符
  • 原文地址:https://www.cnblogs.com/GaiHeiluKamei/p/11108147.html
Copyright © 2011-2022 走看看