duangu1878 2018-07-10 23:02
浏览 46
已采纳

分割一串带有一个副字母,一个副数字的字符串

I’m having a mind blank on this one. I am receiving strings of the format.. AB1234 ABC1234 ABC123 AB12 etc etc. Essentially, flight numbers

They could have one or two letters and anything from 1 to 5 numbers. I want to split the string so that I end up with two strings, one with the numbers and one with the letters.

Any ideas? I’ve looked through these but can’t see one that would do the job https://www.dotnetperls.com/split-go

Update:

Just found and will use this unless there’s a better option. Delete all letters / numbers to create the strings needed https://golangcode.com/how-to-remove-all-non-alphanumerical-characters-from-a-string/

  • 写回答

2条回答 默认 最新

  • 普通网友 2018-07-11 01:43
    关注

    You could take advantage of the fact that Go is a programming language and write a simple Go function. For example,

    package main
    
    import (
        "fmt"
    )
    
    func parseFlight(s string) (letters, numbers string) {
        var l, n []rune
        for _, r := range s {
            switch {
            case r >= 'A' && r <= 'Z':
                l = append(l, r)
            case r >= 'a' && r <= 'z':
                l = append(l, r)
            case r >= '0' && r <= '9':
                n = append(n, r)
            }
        }
        return string(l), string(n)
    }
    
    func main() {
        flights := []string{"AB1234", "ABC1234", "ABC123", "AB12"}
        for _, flight := range flights {
            letters, numbers := parseFlight(flight)
            fmt.Printf("%q: %q %q
    ", flight, letters, numbers)
        }
    }
    

    Playground: https://play.golang.org/p/pDrsqntAP6E

    Output:

    "AB1234": "AB" "1234"
    "ABC1234": "ABC" "1234"
    "ABC123": "ABC" "123"
    "AB12": "AB" "12"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 idea自动补全键位冲突
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页