Golang : Repeat a character by multiple of x factor
In Python, it is pretty easy to repeat some characters inside a string. All you need to do is to multiply the letter with an integer value and the letter will be multiplied/repeated by x number of times
For example:
str = ''.join(['a' * 1, 'b' * 1, 'c' * 2, 'd' * 3, 'e' * 2, 'f' * 4, \
'g' * 5, 'h' * 6, 'i' * 3, 'j' * 7, 'k' * 8, 'l' * 9, 'm' * 10, \
'n' * 11, 'o' * 4, 'p' * 12, 'q' * 13, 'r' * 14, 's' * 15, \
't' * 16, 'u' * 5, 'w' * 17, 'y' * 18, 'z' * 19])
will produce:
abccdddeeffffggggghhhhhhiiijjjjjjjkkkkkkkklllllllllmmmmmmmmmmnnnnnnnnnnnoo
ooppppppppppppqqqqqqqqqqqqqrrrrrrrrrrrrrrsssssssssssssssttttttttttttttttuuuuuw
wwwwwwwwwwwwwwwwyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzz
However, it is not permissible to multiply a letter with integer in Golang. Doing so will generate error such as invalid operation: "join" * 2 (mismatched types string and int)
.
To create multiple instances/repeatition of a letter in Golang, you will have to use the strings.Repeat()
function.
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := []string{"a", "b", "c", "d", "e"}
fmt.Println(strings.Join(str, " "))
// Python way of repeating string by multiple of x will
// not work here
//str2 := []string{"a" * 2, "b", "c", "d", "e"}
// Golang's way of multiplying a string by x factor
str2 := []string{strings.Repeat("a", 2), "b", "c", "d", "e"}
fmt.Println(strings.Join(str2, " "))
a2 := strings.Repeat("a", 2)
b3 := strings.Repeat("b", 3)
c4 := strings.Repeat("c", 4)
d5 := strings.Repeat("d", 5)
e9 := strings.Repeat("e", 9)
str3 := []string{a2, b3, c4, d5, e9}
fmt.Println(strings.Join(str3, " "))
}
Output:
a b c d e
aa b c d e
aa bbb cccc ddddd eeeeeeeee
References:
https://www.socketloop.com/tutorials/golang-how-to-join-strings
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.5k Golang : How to reverse slice or array elements order
+6.6k Mac/Linux/Windows : Get CPU information from command line
+10.9k Golang : Calculate Relative Strength Index(RSI) example
+7.6k Swift : Convert (cast) String to Double
+16.1k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+23.3k Golang : Check if element exist in map
+14.9k Golang : Get all local users and print out their home directory, description and group id
+34.7k Golang : Upload and download file to/from AWS S3
+6.4k Golang : Warp text string by number of characters or runes example
+23.3k Find and replace a character in a string in Go
+30.9k Golang : bufio.NewReader.ReadLine to read file line by line
+5.6k Golang : Markov chains to predict probability of next state example