2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Go言語でキャメルケースをスネークケースに変換する

Last updated at Posted at 2020-06-16

こんばんは、ねじねじおです。

埃をかぶっていたMacBook Proに、VS Codeを入れました。
Go言語でキャメルケースをスネークケースに変換してみます。

import "strings"

func CamelToSnake(s string) string {
	if s == "" {
		return s
	}

	delimiter := "_"
	sLen := len(s)
	var snake string
	for i, current := range s {
		if i > 0 && i+1 < sLen {
			if current >= 'A' && current <= 'Z' {
				next := s[i+1]
				prev := s[i-1]
				if (next >= 'a' && next <= 'z') || (prev >= 'a' && prev <= 'z') {
					snake += delimiter
				}
			}
		}
		snake += string(current)
	}

	snake = strings.ToLower(snake)
	return snake
}

テストも書く。

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestExampleSuccess(t *testing.T) {
	tests := []struct {
		in       string
		expected string
	}{
		{"RememberMe", "remember_me"},
		{"requestID", "request_id"},
		{"HTTPRequest", "http_request"},
		{"HTML5Script", "html5_script"},
	}

	for _, test := range tests {
		res := CamelToSnake(test.in)
		assert.Equal(t, test.expected, res)
	}
}

OK。
ねじねじおでした。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?