对具有相同文本的字符串片段进行编号

huangapple go评论83阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2022年9月27日 23:24:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/73870076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定