All Articles

Cleaning a string in golang with Buffer and Scanner

Alt

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()
}

Benchmarking

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

Share your thoughts šŸ˜‰

Happy coding! šŸš€

Published Aug 7, 2021

Passionate software engineer with expertise in software development, microservice architecture, and cloud infrastructure.