Friday, April 26, 2024
HomeGolangRepeat a string in Go (Golang)

Repeat a string in Go (Golang)



To repeat a given string in Go, you should use the strings.Repeat() perform from the strings package deal.

It takes a string and the variety of instances it must be repeated as arguments and returns the multiplied string as output. The perform panics if depend is detrimental or if len(s) * depend overflows.

Take a look at the next instance:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package deal predominant

import (
    "fmt"
    "strings"
    "unicode/utf8"
)

func predominant() {
    s := "gosamples.dev "
    repeated := strings.Repeat(s, 3)
    lineSeparator := strings.Repeat("-", utf8.RuneCountInString(repeated))

    fmt.Println(repeated)
    fmt.Println(lineSeparator)
}

Output:

gosamples.dev gosamples.dev gosamples.dev 
------------------------------------------

In line 11, we create a brand new multiplied string which is the string "gosamples.dev " repeated 3 times. Then, in line 12, we wish to make a line separator consisting of a repeated - character. Its size must be equal to the variety of characters of the earlier string.

Notice that we use the utf8.RuneCountInString() perform to depend the variety of characters as an alternative of len(). The previous counts the runes (Unicode code factors) within the string, whereas the latter counts the variety of bytes. When counting characters in a string "gosamples.dev gosamples.dev gosamples.dev ", each features will return the identical quantity; nevertheless it’s good to make a behavior of utilizing utf8.RuneCountInString() while you wish to depend the variety of characters. It should forestall incorrect outcomes while you change the enter string:

s := "€€€"
fmt.Println(len(s))
fmt.Println(utf8.RuneCountInString(s))

The € (euro) image is a three-byte character, encoded in UTF-8 with bytes 0xE2, 0x82, 0xAC.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments