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 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型