douxiong2999 2013-10-02 02:42
浏览 51
已采纳

Golang:Go中的函数式编程

I tried something I did in Javascript. But it says http://play.golang.org/p/qlWLI03Dnl

    package main

    import "fmt"
    import "regexp"
    import "strings"

    func swapit(str string) string {
        var validID = regexp.MustCompile(`[a-z]|[A-Z]`)
        return validID.ReplaceAllString(str, func(${0}, ${1}, ${2}) string {
                return (${1}) ? strings.ToUpper(${0}) : strings.ToLower(${0})
            })

    }

    func main() {
        fmt.Println(swapit("hello wOrld."))
        // HELLO WoRLD.

    }

I also tried this removing ? : syntax but still does not work. http://play.golang.org/p/mD6_78zzo1

Does really go not support this? Do I just give up and just bruteforce each character to change cases?

Thanks a lot

  • 写回答

1条回答 默认 最新

  • duanbishai5271 2013-10-02 06:19
    关注

    As @James Henstridge already pointed out, there are multiple problems with your code. This answer will not focus on the errors, but rather a different way of solving the problem.

    If your aim is to learn about using regexp in Go, this answer of mine is useless.
    If your aim is to get learn how to make a function that swaps cases, then I suggest a solution without regexp, utilizing the unicode package instead:

    package main
    
    import (
        "bytes"
        "fmt"
        "unicode"
    )
    
    func SwapCase(str string) string {
        b := new(bytes.Buffer)
    
        for _, r := range str {
            if unicode.IsUpper(r) {
                b.WriteRune(unicode.ToLower(r))
            } else {
                b.WriteRune(unicode.ToUpper(r))
            }
        }
    
        return b.String()
    }
    
    func main() {
        fmt.Println(SwapCase("Hej värLDen."))
    }
    

    Output:

    hEJ VÄRldEN.

    Playground

    This solution will handle all non A-Z characters as well, such as ö-Ö and å-Å.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配