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 å-Å.

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

报告相同问题?

悬赏问题

  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题