如何在golang中替换字符串中的所有字符

huangapple go评论99阅读模式
英文:

How to replace all characters in a string in golang

问题

包 main

import (
"fmt"
"strings"
)

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

英文:
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 "******"?

答案1

得分: 16

通过替换所有字符,您可以得到一个具有相同字符数的字符串,但所有字符都是'*'。因此,只需构造一个具有相同字符长度但所有字符都是'*'的字符串。strings.Repeat()可以重复一个字符串(通过连接它):

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

输出结果(在Go Playground上尝试):

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

请注意,len(s)给出的是UTF-8编码形式的长度,因为这是Go在内存中存储字符串的方式。您可以使用utf8.RuneCountInString()获取字符数。

例如,以下行:

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

输出结果为6 2,因为字符串"世界"需要6个字节来编码(UTF-8),但它只有2个字符。

英文:

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.

答案2

得分: 14

一个简单的方法是不使用正则表达式:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Repeat("*", utf8.RuneCountInString("golang")))
}

更接近你最初想法的方法是:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(".")
	fmt.Println(re.ReplaceAllString("golang", "*"))
}
英文:

A simple way of doing it without something like a regex:

https://play.golang.org/p/B3c9Ket9fp

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Repeat("*", utf8.RuneCountInString("golang")))
}

Something more along the lines of what you were probably initially thinking:

https://play.golang.org/p/nbNNFJApPp

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(".")
	fmt.Println(re.ReplaceAllString("golang", "*"))
}

huangapple
  • 本文由 发表于 2016年4月29日 13:32:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/36930263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定