Skip to content

Instantly share code, notes, and snippets.

@KEINOS
Last active August 4, 2021 10:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KEINOS/5fd419de98e58b650ad279d6c1266179 to your computer and use it in GitHub Desktop.
Save KEINOS/5fd419de98e58b650ad279d6c1266179 to your computer and use it in GitHub Desktop.
[Golang] How to replace all whitespaces into a single space without using regex.

[Golang] How To Replace All Whitespaces Into a Single Space in Go

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

TL; DR

Use strings.Fiels() and join them.

myOutput := strings.Join(strings.Fields(myInput), " ")

TS; DR

func Fields

func Fields(s string) []string

Fields 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)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment