Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all characters in a string in golang

Tags:

string

replace

go

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Replace("golang", "g", "1", -1))
}

How to replace all characters in string "golang" (above string) by * that is it should look like "******"?

like image 563
vijay Avatar asked Apr 29 '16 05:04

vijay


1 Answers

By replacing all characters you would get a string with the same character count, but all being '*'. So simply construct a string with the same character-length but all being '*'. strings.Repeat() can repeat a string (by concatenating it):

ss := []string{"golang", "pi", "世界"}
for _, s := range ss {
    fmt.Println(s, strings.Repeat("*", utf8.RuneCountInString(s)))
}

Output (try it on the Go Playground):

golang ******
pi **
世界 **

Note that len(s) gives you the length of the UTF-8 encoding form as this is how Go stores strings in memory. You can get the number of characters using utf8.RuneCountInString().

For example the following line:

fmt.Println(len("世界"), utf8.RuneCountInString("世界")) // Prints 6 2

prints 6 2 as the string "世界" requires 6 bytes to encode (in UTF-8), but it has only 2 characters.

like image 172
icza Avatar answered Nov 20 '22 22:11

icza