Trimming/replacing repeated whitespaces such as space, tab, line-breaks, etc as one space.
Something like " foo\n\t\t bar\n buzz
" to "foo bar buzz
". But without using regex nor multiple strings.Replace()
.
Use
strings.Fiels()
and join them.
myOutput := strings.Join(strings.Fields(myInput), " ")
func Fields(s string) []stringFields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.
(from: Fields | strings @ golang.org
package main
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
type DataProvider []struct {
input string
expect string
}
func TestLastIndex(t *testing.T) {
DataProvider := []struct {
Input string
Expect string
}{
{
" How about this?",
"How about this?",
},
{
" hoge fuga piyo \n foo\n bar\n buz",
"hoge fuga piyo foo bar buz",
},
}
for _, data := range DataProvider {
expect := data.Expect
result := strings.Fields(data.Input)
actual := strings.Join(result, " ")
assert.Equal(t, expect, actual)
}
}
- View online @ Go Playground