How to remove the first character of a string in Golang

How to remove the first character of a string in Golang

Learn how to remove first the character of a string in GoLang

You have a string, and you need to remove the first character in it. How would you go about doing this?

Solution

Here is the solution I used:

func RemoveFirstChar(input string) string {

	// If input string length is 1 or less return empty string.
	if len(input) <= 1 {
		return ""
	}

	// Return string staring at index 1
	return string([]rune(input)[1:])
}

Test

Here is the test code:

import "testing"

func TestRemoveFirstChar(t *testing.T) {
	// Test table of strings.
	removeFirstCharTests := []struct {
		name     string
		input    string
		expected string
	}{
		{"Test One", "Bob", "ob"},
		{"Empty String Test", "", ""},
		{"One Char String Test", "A", ""},
		{"Other test", "abcdef", "bcdef"},
	}

	// Loop over all test.
	for _, tt := range removeFirstCharTests {
		var got = RemoveFirstChar(tt.input)
		if got != tt.expected {
			t.Fatalf("Got %v, Expected %v.", got, tt.expected)
		}
		t.Logf("TEST PASSED")
	}
}

Source Code

You can find the source code on GitHub

Did you like it? Why don't you try also...

Is String a Palindrome?

Is String a Palindrome?

Learn How to Test if a String is a Palindrome in Go.

How to Find the Maximum Integer Value In a GoLang Slice

How to Find the Maximum Integer Value In a GoLang Slice

Learn to Find the Maximum Integer Value In a GoLang Slice

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.