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

Get The Names Of All The Files Inside A Directory Using GoLang

Get The Names Of All The Files Inside A Directory Using GoLang

Learn how to get list all the file names inside of a directory using golang

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.

How to Convert GoLang Integer to String Conversion

How to Convert GoLang Integer to String Conversion

Learn how to convert integers to strings and how to convert strings to integers in GoLang