go语言如何将ips = "10.0.0.2-10.0.2.3;5.5.16.4;169.168.2.266-169.168.2.288;169.168.2.289 "中的ip去重、计算总个数、将连续的ip合并用-连接,不连续的用;连接
时间: 2024-10-24 19:09:21 浏览: 9
cat4500e-lanbasek9-mz.151-2.SG.rar
在Go语言中,你可以使用切片(slices)、map以及range循环等基本数据结构和控制流程来处理这样的IP字符串。以下是一个步骤性的解决方案:
1. 首先,将IP地址字符串分割成一个切片(slice),去除连续的IP范围并保留单个IP。
```go
func splitIPs(ipStr string) []string {
ips := strings.Split(ipStr, ";")
result := make([]string, 0)
for _, ipRange := range ips {
ranges := strings.Split(ipRange, "-")
if len(ranges) == 2 { // 连续IP范围
start, end, err := strconv.Atoi(strings.TrimSpace(ranges[0])), strconv.Atoi(strings.TrimSpace(ranges[1]))
if err != nil {
panic(err)
}
for i := start; i <= end; i++ {
result = append(result, fmt.Sprintf("%d", i))
}
} else { // 单个或非连续IP
result = append(result, strings.TrimSpace(ipRange))
}
}
return result
}
```
2. 使用map来去重,因为Go语言的map不允许有重复键,所以遍历上述结果集,添加到新的map中,同时记录计数。
```go
func uniqueIPsAndCount(ips []string) (map[string]int, int) {
ipMap := make(map[string]int)
count := 0
for _, ip := range ips {
ipMap[ip]++
count++
}
return ipMap, count
}
```
3. 最后,根据map创建一个新的字符串,包含去重后的IP和总数,对于连续的IP范围用`-`连接,非连续的用`;`。
```go
func formatIPString(ipMap map[string]int, total int) string {
formattedIPs := ""
for ip, _ := range ipMap {
formattedIPs += ip + (strings.HasSuffix(ip, ".") ? "" : ":") + strconv.Itoa(ipMap[ip]) + ";"
}
if total > 1 {
formattedIPs = strings.TrimSuffix(formattedIPs, ";") + " (" + strconv.Itoa(total) + "个)"
} else {
formattedIPs = strings.TrimSuffix(formattedIPs, ";") + " (1个)"
}
return formattedIPs
}
// 示例调用
ips := "10.0.0.2-10.0.2.3;5.5.16.4;169.168.2.266-169.168.2.288;169.168.2.289"
processedIPs := formatIPString(uniqueIPsAndCount(splitIPs(ips))[0], uniqueIPsAndCount(splitIPs(ips))[1])
fmt.Println(processedIPs)
```
阅读全文