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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据