英文:
Numbering a slice of string having same text
问题
我有一个包含一些相同文本元素的字符串切片,例如:
[apple, banana, apple, peer, apple]
我想要做的是通过给它们编号来更新具有相同文本的字符串的名称,如下所示:
[apple, banana, apple2, peer, apple3]
在字符串切片中,我该如何实现这个目标?
英文:
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?
答案1
得分: 0
这应该以非常高效的方式解决了你的问题: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
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论