生成返回字符串函数并循环指定索引字符串
时间:2024-02-26
浏览:167
作者:佚名
你在学习Golang相关的知识吗?本文《生成返回字符串函数并循环指定索引字符串》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
问题内容
func change(a string) string {
// fmt.Println(a)
v := ""
if string(a) == "a" {
return "A"
v += a
}
return ""
}
func main() {
fmt.Println(change("a"))
fmt.Println(change("ab"))
}
实际上我是围棋和编程新手, 现在的输出是 a,但是为什么当我将变量值更改为“ab”时,它不返回任何值,输出必须是“ab”
正确答案
因此,您基本上希望输入中的所有 a 更改为 a。
目前,您只需检查整个字符串是否等于 "a",并且 "ab" 是否不等于 "a"。因此,在第二种情况下,程序以 return "" 结束。
通常,您可以使用 strings.replaceall("abaaba","a","a") 来实现您想要的效果。但出于教育目的,这里有一个“手动”解决方案。
func change(a string) string {
v := "" // our new string, we construct it step by step
for _, c := range a { // loop over all characters
if c != 'a' { // in case it's not an "a" ...
v += string(c) // ... just append it to the new string v
} else {
v += "a" // otherwise append an "a" to the new string v
}
}
return v
}
另请注意,c 的类型为 rune,因此必须使用 string(c) 转换为 string。
编辑:正如评论中所述,实际上这不是构建新 string 的最佳方法。除了从 rune 转换为 string 的麻烦之外,每次我们附加一些东西并删除旧的东西时,我们都会创建一个新的 string 。相反,我们只想创建一次 string - 在最后,当我们确切知道结果 string 的样子时。
因此,我们应该使用字符串生成器。为了避免混淆,这里有一个单独的示例:
func change(a string) string {
var resultBuilder strings.Builder
for _, c := range a { // loop over all characters
if c != 'a' { // in case it's not an "a" ...
resultBuilder.WriteRune(c) // ... just append it to the new string v
} else {
resultBuilder.WriteString("A") // otherwise append an "A" to the new string v
}
}
return resultBuilder.String() // Create the final string once everything is set
}今天关于《生成返回字符串函数并循环指定索引字符串》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
