github.com/richardwilkes/toolbox@v1.121.0/txt/collapse_spaces.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package txt
    11  
    12  import "strings"
    13  
    14  // CollapseSpaces removes leading and trailing spaces and reduces any runs of two or more spaces to a single space.
    15  func CollapseSpaces(in string) string {
    16  	var buffer strings.Builder
    17  	lastWasSpace := false
    18  	for i, r := range in {
    19  		if r == ' ' {
    20  			if !lastWasSpace {
    21  				if i != 0 {
    22  					buffer.WriteByte(' ')
    23  				}
    24  				lastWasSpace = true
    25  			}
    26  		} else {
    27  			buffer.WriteRune(r)
    28  			lastWasSpace = false
    29  		}
    30  	}
    31  	str := buffer.String()
    32  	if lastWasSpace && str != "" {
    33  		str = str[:len(str)-1]
    34  	}
    35  	return str
    36  }