mirror of
https://github.com/go-sylixos/elvish.git
synced 2024-12-13 01:40:31 +08:00
Add util.NthRune
This commit is contained in:
parent
a4cfc41673
commit
ea9dabd261
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user