0
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?

GoでTrimを使う

Posted at

はじめに

表題通り、GoでTrimを使います。あー、Trimねってなるんですが、いざ使うと。。。あれなんだっけとなったので、備忘録も兼ねて残しておきます。

コード

main.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	// 余分な空白・改行の除去
	fmt.Println(strings.TrimSpace("  hello \n\t")) // => "hello"

	// 先頭の固定文字列を1回だけ除去
	fmt.Println(strings.TrimPrefix("prefix_value", "prefix_")) // => "value"

	// 末尾の固定文字列を1回だけ除去
	fmt.Println(strings.TrimSuffix("report.csv", ".csv")) // => "report"

	// 先頭と末尾から、集合に含まれるいずれかの文字を繰り返し除去
	fmt.Println(strings.Trim("--abc--", "-")) // => "abc"

	// 左側のみ/右側のみを対象に除去
	fmt.Println(strings.TrimLeft("///path", "/"))  // => "path"
	fmt.Println(strings.TrimRight("path///", "/")) // => "path"
}

package main

import (
	"strings"
	"testing"
)

func TestTrim_All(t *testing.T) {
	cases := []struct {
		name string
		op   string // 実行するトリム関数
		in   string // 入力文字列
		arg  string // プレフィックス/サフィックス/カットセット
		want string // 期待値
	}{
		{name: "前後の空白を除去 (TrimSpace)", op: "TrimSpace", in: "  hello \n\t", want: "hello"},
		{name: "先頭の接頭辞を1回だけ除去 (TrimPrefix)", op: "TrimPrefix", in: "prefix_value", arg: "prefix_", want: "value"},
		{name: "末尾の接尾辞を1回だけ除去 (TrimSuffix)", op: "TrimSuffix", in: "report.csv", arg: ".csv", want: "report"},
		{name: "指定文字を両端から除去 (Trim)", op: "Trim", in: "--abc--", arg: "-", want: "abc"},
		{name: "左側のみ指定文字を除去 (TrimLeft)", op: "TrimLeft", in: "///path", arg: "/", want: "path"},
		{name: "右側のみ指定文字を除去 (TrimRight)", op: "TrimRight", in: "path///", arg: "/", want: "path"},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			var got string
			switch tc.op {
			case "TrimSpace":
				got = strings.TrimSpace(tc.in)
			case "TrimPrefix":
				got = strings.TrimPrefix(tc.in, tc.arg)
			case "TrimSuffix":
				got = strings.TrimSuffix(tc.in, tc.arg)
			case "Trim":
				got = strings.Trim(tc.in, tc.arg)
			case "TrimLeft":
				got = strings.TrimLeft(tc.in, tc.arg)
			case "TrimRight":
				got = strings.TrimRight(tc.in, tc.arg)
			default:
				t.Fatalf("unknown op: %s", tc.op)
			}

			if got != tc.want {
				t.Fatalf("[%s] テストケース=%q input=%q arg=%q 実行結果=%q 期待値=%q", tc.op, tc.name, tc.in, tc.arg, got, tc.want)
			}
		})
	}
}

0
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
0
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?