乐趣区

关于go:go-stringsToLower-原理解析

一、ASCII 介绍
英语的字母大小写转化,是咱们常遇到的字符串解决状况。

一、go 中解决字符串 转化小写

func ToLower(s string) string {b := strings.Builder{}
    b.Grow(len(s))
    for i := 0; i < len(s); i++ {c := s[i]
        if 'A' <= c && c <= 'Z' {c += 'a' - 'A'}
        b.WriteByte(c)
    }
    return b.String()}

测试函数:

import "testing"

func TestToLower(t *testing.T) {
    type args struct {s string}
    tests := []struct {
        name string
        args args
        want string
    }{{"1", args{s: "A"}, "a"},
        {"1", args{s: "Aa"}, "aa"},
        {"1", args{s: "Aa0"}, "aa0"},
        {"1", args{s: ")A_$"}, ")a_$"},
        {"1", args{s: "0000"}, "0000"},
        {"1", args{s: "哈哈 a"}, "哈哈 a"},
        {"1", args{s: "哈哈 A 啊啊"}, "哈哈 a 啊啊"},
    }
    for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {if got := ToLower(tt.args.s); got != tt.want {t.Errorf("ToLower() = %v, want %v", got, tt.want)
            }
        })
    }
}
退出移动版