zoukankan      html  css  js  c++  java
  • go 字符串拼接

    func main() {
      s1 := "Hello" + " " + "World"
      fmt.Println(s1)  //Hello World
    
      ss := []string{"Hello", "World"}
      fmt.Println(strings.Join(ss, " ")) //Hello World
    }

    可以拼接任意多个字符串。但是+的缺点是待拼接的字符串必须是已知的。

    另一种方式就是使用标准库strings包中的Join()函数,这个函数接受一个字符串切片和一个分隔符,将切片中的元素拼接成以分隔符分隔的单个字符串

    func ConcatWithMultiPlus() {
      var s string
      for i := 0; i < 10; i++ {
        s += "hello"
      }
    }
    
    func ConcatWithOnePlus() {
      s1 := "hello"
      s2 := "hello"
      s3 := "hello"
      s4 := "hello"
      s5 := "hello"
      s6 := "hello"
      s7 := "hello"
      s8 := "hello"
      s9 := "hello"
      s10 := "hello"
      s := s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10
      _ = s
    }
    
    func ConcatWithJoin() {
      s := []string{"hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello"}
      _ = strings.Join(s, "")
    }

    三种拼接字符串的方式

  • 相关阅读:
    day 49
    day 48
    day 46
    IOC和DI到底是什么?
    堆排序算法
    快速排序算法
    java中try-catch-finally中的return语句
    归并排序算法
    选择排序算法
    冒泡排序算法
  • 原文地址:https://www.cnblogs.com/kevin-yang123/p/14827663.html
Copyright © 2011-2022 走看看