简体   繁体   中英

Numbering a slice of string having same text [closed]

I have a slice of string containing some elements with the same text such as: [apple, banana, apple, peer, apple] what I would like to do is update the names of the string having the same text by number them in this way: [apple, banana, apple2, peer, apple3] how can I do this in a slice of strings?

This should solve your problem in a very efficient manner: O(N) package main

import (
    "fmt"
    "strconv"
)
func main() {
    testStringSlice := []string{"apple", "banana", "apple", "peer", "apple"}
    outputStringSlice := numberItems(testStringSlice)
    fmt.Println(outputStringSlice)
}

func numberItems (arr []string) []string{
    m := make(map[string]int)
    for idx, item := range arr {
            if count, ok := m[item]; ok {
                    m[item] = count + 1
                    arr[idx] = item + strconv.Itoa(m[item])
            } else {
                    m[item] = 1
            }
    }
    return arr
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM