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

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

图片转代码服务由CSDN问答提供 功能建议

我尝试了用Java语言编写的内容。 但是它表示 http://play.golang.org/p/qlWLI03Dnl

 包main 
  
导入“ fmt” 
导入“ regexp” 
导入“字符串” 
 
 func swapit(str字符串)字符串{
 var validID = regexp.MustCompile(`[az] | [AZ]`)\\  n返回validID.ReplaceAllString(str,func($ {0},$ {1},$ {2})字符串{
 return($ {1})?strings.ToUpper($ {0}):strings.ToLower  ($ {0})
})
 
} 
 
 func main(){
 fmt.Println(swapit(“ hello wOrld。”))
 // HELLO WoRLD。
 
  } 
   
 
 

我也尝试过此删除操作? :语法,但仍然无法正常工作。 http://play.golang.org/p/mD6_78zzo1

真的不支持此吗? 我只是放弃并且只是蛮力地改变每个角色的大小写吗?

非常感谢

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题