Skip to content

Commit 695cfc1

Browse files
authored
Merge pull request #115 from xushiwei/q
stringutil.Capitalize
2 parents ef37901 + 33dcf91 commit 695cfc1

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

stringutil/string_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,18 @@ import (
2222
"testing"
2323
)
2424

25+
func TestCapitalize(t *testing.T) {
26+
if ret := Capitalize(""); ret != "" {
27+
t.Fatal("Capitalize:", ret)
28+
}
29+
if ret := Capitalize("hello"); ret != "Hello" {
30+
t.Fatal("Capitalize:", ret)
31+
}
32+
if ret := Capitalize("Hello"); ret != "Hello" {
33+
t.Fatal("Capitalize:", ret)
34+
}
35+
}
36+
2537
func TestConcat(t *testing.T) {
2638
if ret := Concat("1"); ret != "1" {
2739
t.Fatal("Concat(1):", ret)

stringutil/transform.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Copyright 2025 Qiniu Limited (qiniu.com)
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package stringutil
18+
19+
import (
20+
"unicode"
21+
"unicode/utf8"
22+
)
23+
24+
// Capitalize returns a copy of the string str with the first letter mapped to
25+
// its upper case.
26+
func Capitalize(str string) string {
27+
c, nc := utf8.DecodeRuneInString(str)
28+
if unicode.IsUpper(c) || c == utf8.RuneError {
29+
return str
30+
}
31+
ret := make([]byte, len(str))
32+
nr := utf8.EncodeRune(ret, unicode.ToUpper(c))
33+
ret = append(ret[:nr], str[nc:]...)
34+
return String(ret)
35+
}

0 commit comments

Comments
 (0)