'How to remove duplicated spaces from a string without removing new lines characters
I can read here: How to remove redundant spaces/whitespace from a string in Golang? that I can use regex or strings.Fields to remove duplicated spaces from strings.
I need to know a fast (performances matter here) way to remove ONLY duplicated (or more) spaces from a (maybe long) string and NOT remove new lines characters like \n.
Example:
"I have
[SPACE][SPACE][SPACE]duplicated spaces[SPACE][SPACE][SPACE]as you can see" => "I have[SPACE]duplicated spaces[SPACE]as you can see""I have
[SPACE][SPACE][SPACE]new lines\n\ntoo" => "I have[SPACE]new lines\n\ntoo"
Solution 1:[1]
strings.ReplaceAll(strings.Join(strings.FieldsFunc(text, func(r rune) bool {
if r == '\n' {
return false
}
return unicode.IsSpace(r)
} ), " ")," \n", "\n")
r := regexp.MustCompile("( ){2,}")
r.ReplaceAllString(input, " ")
strings.FieldsFunc seems to be a lot faster than regexp
cpu: Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
BenchmarkRegexp
BenchmarkRegexp-8 841189 1299 ns/op
BenchmarkFields
BenchmarkFields-8 3375925 355.4 ns/op
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
