'Can Golang multiply strings like Python can?
Python can multiply strings like so:
Python 3.4.3 (default, Mar 26 2015, 22:03:40)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'my new text is this long'
>>> y = '#' * len(x)
>>> y
'########################'
>>>
Can Golang do the equivalent somehow?
Solution 1:[1]
Yes, it can, although not with an operator but with a function in the standard library.
It would be very easy with a simple loop, but the standard library provides you a highly optimized version of it: strings.Repeat().
Your example:
x := "my new text is this long"
y := strings.Repeat("#", len(x))
fmt.Println(y)
Try it on the Go Playground.
Notes: len(x) is the "bytes" length (number of bytes) of the string (in UTF-8 encoding, this is how Go stores strings in memory). If you want the number of characters (runes), use utf8.RuneCountInString().
Solution 2:[2]
Yup. The strings package has a Repeat function.
Solution 3:[3]
you can use the string package. it has a repeat functionhere
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ShadowRanger |
| Solution 3 | Friska S E Putri |
