Golang shorts #3 — Extended split function

There is split function provided by the strings package but what if I don’t want to split the string if it is between quotes. For example there is a string test1;test2;”test3;test4”;test5 and I want to split it based on the ; delimiter but I don’t want to split the test3;test4 because it’s between the quotes.

I think I found the best solution. It’s using the strings package FieldsFunc function which allow you to define the rule what you want to apply whether and where to split the string. The solution assume there is a starting quote and an ending quote.

func Split(str string, delimiter rune) []string {
var isQuote = false
f := func(c rune) bool {
if c == '"' {
if isQuote {
isQuote = false
} else {
isQuote = true
}
}
if !isQuote {
return c == delimiter
}
return false
}
 result := strings.FieldsFunc(str, f)
 for k, v := range result {
if strings.Contains(v, `"`) {
result[k] = strings.Replace(v, `"`, "", -1)
}
}
 return result
}

What is it doing?

Getting the string and the delimiter as string and rune. It’s rune, because the FieldFunc define the function with rune parameter. Setup the isQuote variable which handle the section and determine it is between quotes or not. The function for the FieldFunc is returning true if the rune is delimiter, if the isQuote is false. It returns false if the isQuote is true, because in this case the section between quotes.

After that it passes the string and this helper function to the FieldFunc and getting the result. The FieldFunc doesn’t remove the quotes so in the following for loop I remove them.

Like what you read? Give PumpkinSeed a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.