Created
February 2, 2026 11:50
-
-
Save varfrog/ff4a9f96f8e708c5ecf1cc5c1a1475db to your computer and use it in GitHub Desktop.
Collapse spaces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package collapse | |
| import ( | |
| "strings" | |
| ) | |
| func CollapseContains(s string) string { | |
| for strings.Contains(s, " ") { | |
| s = strings.ReplaceAll(s, " ", " ") | |
| } | |
| return s | |
| } | |
| // Single-pass using strings.Builder (Unicode-safe) | |
| func CollapseBuilder(s string) string { | |
| var b strings.Builder | |
| b.Grow(len(s)) | |
| prevSpace := false | |
| for _, r := range s { | |
| if r == ' ' { | |
| if prevSpace { | |
| continue | |
| } | |
| prevSpace = true | |
| } else { | |
| prevSpace = false | |
| } | |
| b.WriteRune(r) | |
| } | |
| return b.String() | |
| } | |
| func CollapseFields(s string) string { | |
| return strings.Join(strings.Fields(s), " ") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment