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

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格