Skip to content

Commit

Permalink
feat: add IsLetter() and IsLetterOrNumeric()
Browse files Browse the repository at this point in the history
  • Loading branch information
fufuok committed Aug 13, 2024
1 parent 6a3155f commit 7d81d28
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 6 deletions.
32 changes: 29 additions & 3 deletions strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,39 @@ func Reverse(s string) string {
return B2S(b)
}

// IsNumeric 检查字符串是否全是数字: 0-9
// IsNumeric 检查字符串是否全是 ASCII 数字: 0-9
func IsNumeric(s string) bool {
if s == "" {
return false
}
for _, char := range s {
if char < '0' || char > '9' {
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}

// IsLetter 检查字符串是否全是 ASCII 字母
func IsLetter(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
return false
}
}
return true
}

// IsLetterOrNumeric 检查字符串是否全是 ASCII 字母或数字
func IsLetterOrNumeric(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') {
return false
}
}
Expand Down
43 changes: 40 additions & 3 deletions strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -552,8 +552,8 @@ func TestSubString(t *testing.T) {
func TestIsNumeric(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
s string
isNumeric bool
s string
res bool
}{
{"", false},
{" 123", false},
Expand All @@ -564,7 +564,44 @@ func TestIsNumeric(t *testing.T) {
{"1234567890777", true},
{"0", true},
} {
assert.Equal(t, tt.isNumeric, IsNumeric(tt.s))
assert.Equal(t, tt.res, IsNumeric(tt.s))
}
}

func TestIsLetter(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
s string
res bool
}{
{"", false},
{" Abc", false},
{"A bc", false},
{"Hello123", false},

{"aBc", true},
{"z", true},
} {
assert.Equal(t, tt.res, IsLetter(tt.s))
}
}

func TestIsLetterOrNumeric(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
s string
res bool
}{
{"", false},
{" Abc", false},
{"A 12", false},

{"Hello123", true},
{"aBc", true},
{"1230", true},
{"z", true},
} {
assert.Equal(t, tt.res, IsLetterOrNumeric(tt.s), tt.s)
}
}

Expand Down

0 comments on commit 7d81d28

Please sign in to comment.