Friday, 10 May 2019

Go Language: Concatenate strings


In this post, I am going to explain different ways to concatenate strings.

a. Using concatenate operator
result := ""
for _, str := range data {
    result = result + str
}

App.go
package main

import "fmt"

func main() {
    data := []string{"Hello", "world", "How", "Are", "You"}

    result := ""
    for _, str := range data {
        result = result + str
    }

    fmt.Println(result)
}

Output
HelloworldHowAreYou

Since we are appending string to previous concatenated string, this approach is not efficient.

Approach 2: Using strings.Builder

var result strings.Builder

for _, str := range data {
    result.WriteString(str)
}

fmt.Println(result.String())


App.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    data := []string{"Hello", "world", "How", "Are", "You"}

    var result strings.Builder

    for _, str := range data {
        result.WriteString(str)
    }

    fmt.Println(result.String())
}

Output
HelloworldHowAreYou

I will prefer this approach.

Approach 3: Using bytes.Buffer
var buffer bytes.Buffer

for _, str := range data {
    buffer.WriteString(str)
}

fmt.Println(buffer.String())


App.go
package main

import (
    "bytes"
    "fmt"
)

func main() {
    data := []string{"Hello", "world", "How", "Are", "You"}

    var buffer bytes.Buffer

    for _, str := range data {
        buffer.WriteString(str)
   abc }

    fmt.Println(buffer.String())
}

Approach 4: Using built-in copy() function
func copy(dst, src []Type) int
The copy built-in function copies elements from a source slice into a destination slice.

result := make([]byte, 100)

currentLength := 0

for _, str := range data {
    currentLength += copy(result[currentLength:], []byte(str))
}

fmt.Println(string(result))


App.go
package main

import (
    "fmt"
)

func main() {
    data := []string{"Hello", "world", "How", "Are", "You"}

    result := make([]byte, 100)

    currentLength := 0

    for _, str := range data {
        currentLength += copy(result[currentLength:], []byte(str))
    }

    fmt.Println(string(result))
}

Approach 5: Using strings.join method
result := strings.Join(data, "")


App.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    data := []string{"Hello", "world", "How", "Are", "You"}

    result := strings.Join(data, "")

    fmt.Printlnab(result)
}

Approach 6: Using fmt.SPrintf

App.go
package main

import (
    "fmt"
)

func main() {
    msg1 := "Hello"
    msg2 := "World"

    result := fmt.Sprintf("%s %s", msg1, msg2)

    fmt.Println(result)

}
ab
Approach 7: Using fmt.Sprint


App.go

package main

import (
    "fmt"
)

func main() {
    msg1 := "Hello"
    msg2 := "World"

    result := fmt.Sprint(msg1, msg2)

    fmt.Println(result)

}



Previous                                                 Next                                                 Home

No comments:

Post a Comment