All Articles

Cleaning a string in golang with Buffer and Scanner


I was looking for a while for different ways of cleaning a string in Golang from listed symbols and did find anything fast. Therefore as a regular developer, Iā€™m just reinventing a wheel.

And here is the solution:

func ClearString(str string, symbols []string) string { scanner := bufio.NewScanner(strings.NewReader(str)) scanner.Split(bufio.ScanRunes) var buf bytes.Buffer out: for scanner.Scan() { t := scanner.Text() for _, s := range symbols { if s == t { continue out } } buf.WriteString(scanner.Text()) } return buf.String() }


BenchmarkClearString BenchmarkClearString-16 200814 5116 ns/op 4416 B/op 5 allocs/op PASS

Share your thoughts šŸ˜‰

Happy coding! šŸš€