So I have a function that removes punctuation from a string and puts those punctuation characters and their index into two slices:
func removeAndIndexPunctuation(word string) (string, []rune, []int) {
// Index punctuation
numberOfPunct := 0
for _, char := range word {
if unicode.IsPunct(char) {
numberOfPunct += 1
}
}
punctuations := make([]rune, numberOfPunct)
punctuationIndex := make([]int, numberOfPunct)
x := 0
for i, char := range word {
if unicode.IsPunct(char) {
punctuations[x] = char
punctuationIndex[x] = i
x += 1
}
}
// Remove all punctuation from word string
res := r.ReplaceAllString(word, "")
return res, punctuations, punctuationIndex
}
In order to make and populate the slices I have to run two for loops, one for counting the number of punctuations so I can make the array the correct length and then another that's pretty much the same except now I populate the slices.
In Python though I don't need two for loops since Python supports "dynamic arrays":
def removeAndIndexPunctuation(word):
punctuations = []
# Index punctuation
for i, char in enumerate(word):
if char in string.punctuation:
punctuations.append((char, i))
# Remove all punctuation from word string
word = word.encode("utf-8").translate(None, string.punctuation).decode("utf-8")
return word, punctuations
So I just want to make sure, in this case in golang, do I absolutely need two for loops because it doesn't support dynamic arrays or am I missing something? Or in other words, If I'm looping over a set of characters and adding some to an array/slice, do I really need two loops, one for counting the number of characters for setting the length of the slice, and one for populating the slice?
I come from Python and am learning Go.