Go String 的一些方法 和 格式化输出

60 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第20天,点击查看活动详情 今天在这里整理下 Go 中 String 的用法,字符串的输出操作,一些常用的方法。主要用到fmt包。

package main
import ( 
    "fmt" 
    s "strings" 
) 
func main() { 
    /* Need to import strings as s */ 
    fmt.Println(s.Contains("test", "e")) 
    /* Build in */ 
    fmt.Println(len("hello")) // => 5 
    // Outputs: 101 fmt.Println("hello"[1]) // Outputs: e  
    fmt.Println(string("hello"[1])) 
}

String

  • 判断字符串是否在目标串儿中。
Contains("test", "es") # -> true
  • 统计字符
Count("test", "t")  # -> 2
  • 判断前缀
HasPrefix("test", "te")  # -> true
  • 判断后缀
HasSuffix("test", "st") # -> true
  • 位置
Index("test", "e") # -> 1
  • 拼接字符串
Join([]string{"a", "b"}, "-") # -> a-b
  • 重复
Repeat("a", 5) # -> aaaaa
  • 代替
Replace("foo", "o", "0", -1) # -> f00
Replace("foo", "o", "0", 1)  # -> f0o
  • 分割
Split("a-b-c-d-e", "-")  # -> [a b c d e]
  • 转换小写
ToLower("TEST") # -> test
  • 转换大写
ToUpper("test") # -> TEST
package main 
import ( 
    "fmt" 
    "os" 
) 
type point struct { 
    x, y int 
} 
func main() { 
    p := point{1, 2} 
    fmt.Printf("%v\n", p) // => {1 2} 
    # bool:                    %t
    # int, int8 etc.:          %d
    # uint, uint8 etc.:        %d, %#x if printed with %#v
    # float32, complex64, etc: %g
    # string:                  %s
    # chan:                    %p
    # pointer:                 %p

    fmt.Printf("%+v\n", p) // => {x:1 y:2} 
    fmt.Printf("%#v\n", p) // => main.point{x:1, y:2} 
    fmt.Printf("%T\n", p) // => main.point 
    fmt.Printf("%t\n", true) // => TRUE 
    fmt.Printf("%d\n", 123) // => 123 
    fmt.Printf("%b\n", 14) // => 1110 
    fmt.Printf("%c\n", 33) // => ! 
    fmt.Printf("%x\n", 456) // => 1c8 
    
    fmt.Printf("%f\n", 78.9) // => 78.9
    # %f     default width, default precision
    # %9f    width 9, default precision
    # %.2f   default width, precision 2
    # %9.2f  width 9, precision 2
    # %9.f   width 9, precision 0

    fmt.Printf("%e\n", 123400000.0) // => 1.23E+08 
    fmt.Printf("%E\n", 123400000.0) // => 1.23E+08 
    fmt.Printf("%s\n", "\"string\"") // => "string" 
    fmt.Printf("%q\n", "\"string\"") // => "\"string\"" 
    fmt.Printf("%x\n", "hex this") // => 6.86578E+15 
    fmt.Printf("%p\n", &p) // => 0xc00002c040 
    fmt.Printf("|%6d|%6d|\n", 12, 345) // => | 12| 345|
    fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) // => | 1.20| 3.45|
    fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) // => |1.20 |3.45 | 
    fmt.Printf("|%6s|%6s|\n", "foo", "b") // => | foo| b| 
    fmt.Printf("|%-6s|%-6s|\n", "foo", "b") // => |foo |b | 

    fmt.Sprintf("%[2]d %[1]d\n", 11, 22) // => "22 11"
    
    s := fmt.Sprintf("a %s", "string") 
    fmt.Println(s) 
    fmt.Fprintf(os.Stderr, "an %s\n", "error") }