Add util.NthRune

This commit is contained in:
Cheer Xiao 2014-09-21 13:26:47 +02:00
parent a4cfc41673
commit ea9dabd261
2 changed files with 36 additions and 0 deletions

View File

@ -69,3 +69,18 @@ func SubstringByRune(s string, low, high int) (string, error) {
}
return s[bLow:bHigh], nil
}
// NthRune returns the n-th rune of s.
func NthRune(s string, n int) (rune, error) {
if n < 0 {
return 0, IndexOutOfRange
}
var j int
for _, r := range s {
if j == n {
return r, nil
}
j++
}
return 0, IndexOutOfRange
}

View File

@ -46,3 +46,24 @@ func TestSubstringByRune(t *testing.T) {
}
}
}
var NthRuneTests = []struct {
s string
n int
wantedRune rune
wantedErr error
}{
{"你好世界", -1, 0, IndexOutOfRange},
{"你好世界", 0, '你', nil},
{"你好世界", 4, 0, IndexOutOfRange},
}
func TestNthRune(t *testing.T) {
for _, tt := range NthRuneTests {
r, e := NthRune(tt.s, tt.n)
if r != tt.wantedRune || e != tt.wantedErr {
t.Errorf("NthRune(%q, %v) => (%q, %v), want (%q, %v)",
tt.s, tt.n, r, e, tt.wantedRune, tt.wantedErr)
}
}
}