Home  >  Article  >  Backend Development  >  How to repeat a string in go language

How to repeat a string in go language

青灯夜游
青灯夜游Original
2023-01-13 16:08:542038browse

In the Go language, you can use the Repeat() function in the Strings package to repeat a string; this function can repeat a string a specified number of times

How to repeat a string in go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

In the go language, you can use the Repeat() function in the Strings package to repeat a string.

Strings.Repeat() function can repeat a string a specified number of times.

func Repeat(s string, count int) string
Parameters Description
s Original string.
count The number of times to repeat.

Return value

  • The new string returned after repeating count times.

Example 1: Repeat string 4 times

In this program, we will use strings.Repeat() function by specified number of times Repeats the specified string and prints the results on the console screen.

// Golang program to demonstrate the
// strings.Repeat() function

package main

import "fmt"
import "strings"

func main() {
    var str string = "India "
    var result string

    result = strings.Repeat(str, 4)

    fmt.Println("String After repetition:", result)
}

How to repeat a string in go language

Explanation:

  • In the above program, we declared the package main. The main package is used to tell the Go language compiler that this package must be compiled and generate an executable file. Here we have imported the fmt package which contains the fmt package files and then we can use the functions related to the fmt package.

  • In the main() function, we created two variables str and result. Then we use the strings.Repeat() function to repeat the specified string 4 times and assign it to the result variable. After that, we print the results on the console screen.

Example 2: Repeat the string 0 times

// Golang program to demonstrate the
// strings.Repeat() function

package main

import "fmt"
import "strings"

func main() {
    var str string = "India "
    var result string

    result = strings.Repeat(str, 0)

    fmt.Println("String After repetition:", result)
}

How to repeat a string in go language

It can be seen that using the string The strings.Repeat() function repeats the variable str 0 times and returns an empty string.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of How to repeat a string in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn