Den Dribbles

Go Basic Strings

January 22, 2019

This is a simple example of the implementation of some basic functions using the strings package. The unicode package is used for the example using runes.

If building a file, ensure to have the correct imports and package name:

package stringexamples

import (
	"strings"
	"unicode"
)

…and for testing:

package stringexamples

import (
	"testing"
)

Compare

// Test module
func TestStringsCompare(t *testing.T) {
	a := "Hello, World!"
	b := "Hello, World!"
	if CompareStrings(a, b) != 0 {
		t.Fatalf("Expected 0")
	}

	a = "Hello, World!"
	b = "Hello, Worl!"
	if CompareStrings(a, b) != 1 {
		t.Fatalf("Expected 1")
	}

	a = "Hello, World!"
	b = "Hello, World!!"
	if CompareStrings(a, b) != -1 {
		t.Fatalf("Expected -1")
	}
}

// CompareStrings compares two string values and returns an int
func CompareStrings(a string, b string) int {
	return strings.Compare(a, b)
}

Contains

// Test module
func TestContainsString(t *testing.T) {
	a := "Hello, World!"
	b := "Hello, World"
	if ContainsString(a, b) != true {
		t.Fatalf("Expected true")
	}

	a = "Hello, World!"
	b = "Hway"
	if ContainsString(a, b) != false {
		t.Fatalf("Expected false")
	}
}

// ContainsString checks if string contains substr
func ContainsString(s string, substr string) bool {
	return strings.Contains(s, substr)
}

Join

// Test module
func TestJoinString(t *testing.T) {
	a := []string{"Hello", "World!"}
	b := "Hello, World!"

	res := JoinString(a, ", ")

	if res != b {
		t.Fatalf("Expected %s but got %s", b, res)
	}
}

// JoinString turns a string slice into a string
func JoinString(str []string, de string) string {
	return strings.Join(str, de)
}

Split

// Test module
func TestSplitString(t *testing.T) {
	a := "Hello World!"
	b := []string{"Hello", "World!"}

	res := SplitString(a, " ")

	for i, v := range res {
		if v != b[i] {
			t.Fatalf("Expected string %s but got %s", v, b[i])
		}
	}
}

// SplitString turns a string in a []string with delimiter
func SplitString(str string, de string) []string {
	return strings.Split(str, de)
}

Lower case a string using Map

// Test module
func TestMapToLowerString(t *testing.T) {
	a := "Hello, World!"
	b := "hello, world!"

	res := MapOverStringToLower(a)

	if res != b {
		t.Fatalf("Expected %s but got %s", b, res)
	}
}

// MapOverStringToLower uses map to lower case a string
func MapOverStringToLower(str string) string {
	toLower := func(r rune) rune {
		return unicode.ToLower(r)
	}

	return strings.Map(toLower, str)
}

A personal blog on all things of interest. Written by Dennis O'Keeffe, Follow me on Twitter