为了账号安全,请及时绑定邮箱和手机立即绑定

我想为一些索引字符串循环生成返回字符串函数

我想为一些索引字符串循环生成返回字符串函数

Go
喵喔喔 2023-03-15 13:46:41
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”
查看完整描述

1 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

因此,您基本上希望a输入中的所有 s 都更改为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

}

另请注意cis 类型rune,因此必须转换为stringwith string(c)。


编辑:如评论中所述,实际上这不是构建新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

}


查看完整回答
反对 回复 2023-03-15
  • 1 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信