Skip to content

Commit

Permalink
Merge pull request #115 from xushiwei/q
Browse files Browse the repository at this point in the history
stringutil.Capitalize
  • Loading branch information
xushiwei authored Jan 12, 2025
2 parents ef37901 + 33dcf91 commit 695cfc1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
12 changes: 12 additions & 0 deletions stringutil/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ import (
"testing"
)

func TestCapitalize(t *testing.T) {
if ret := Capitalize(""); ret != "" {
t.Fatal("Capitalize:", ret)
}
if ret := Capitalize("hello"); ret != "Hello" {
t.Fatal("Capitalize:", ret)
}
if ret := Capitalize("Hello"); ret != "Hello" {
t.Fatal("Capitalize:", ret)
}
}

func TestConcat(t *testing.T) {
if ret := Concat("1"); ret != "1" {
t.Fatal("Concat(1):", ret)
Expand Down
35 changes: 35 additions & 0 deletions stringutil/transform.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Copyright 2025 Qiniu Limited (qiniu.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package stringutil

import (
"unicode"
"unicode/utf8"
)

// Capitalize returns a copy of the string str with the first letter mapped to
// its upper case.
func Capitalize(str string) string {
c, nc := utf8.DecodeRuneInString(str)
if unicode.IsUpper(c) || c == utf8.RuneError {
return str
}
ret := make([]byte, len(str))
nr := utf8.EncodeRune(ret, unicode.ToUpper(c))
ret = append(ret[:nr], str[nc:]...)
return String(ret)
}

0 comments on commit 695cfc1

Please sign in to comment.