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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料