Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 285aad1

Browse files
aiskncw
authored andcommitted
py: Implement str.count
1 parent 43d2d61 commit 285aad1

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

py/string.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,13 @@ func init() {
148148
return Bool(false), nil
149149
}, 0, "endswith(suffix[, start[, end]]) -> bool")
150150

151+
StringType.Dict["count"] = MustNewMethod("count", func(self Object, args Tuple) (Object, error) {
152+
return self.(String).Count(args)
153+
}, 0, `count(sub[, start[, end]]) -> int
154+
Return the number of non-overlapping occurrences of substring sub in
155+
string S[start:end]. Optional arguments start and end are
156+
interpreted as in slice notation.`)
157+
151158
StringType.Dict["find"] = MustNewMethod("find", func(self Object, args Tuple) (Object, error) {
152159
return self.(String).find(args)
153160
}, 0, `find(...)
@@ -612,6 +619,40 @@ func (s String) M__contains__(item Object) (Object, error) {
612619
return NewBool(strings.Contains(string(s), string(needle))), nil
613620
}
614621

622+
func (s String) Count(args Tuple) (Object, error) {
623+
var (
624+
pysub Object
625+
pybeg Object = Int(0)
626+
pyend Object = Int(s.len())
627+
pyfmt = "s|ii:count"
628+
)
629+
err := ParseTuple(args, pyfmt, &pysub, &pybeg, &pyend)
630+
if err != nil {
631+
return nil, err
632+
}
633+
634+
var (
635+
beg = int(pybeg.(Int))
636+
end = int(pyend.(Int))
637+
size = s.len()
638+
)
639+
if beg > size {
640+
beg = size
641+
}
642+
if end < 0 {
643+
end = size
644+
}
645+
if end > size {
646+
end = size
647+
}
648+
649+
var (
650+
str = string(s.slice(beg, end, s.len()))
651+
sub = string(pysub.(String))
652+
)
653+
return Int(strings.Count(str, sub)), nil
654+
}
655+
615656
func (s String) find(args Tuple) (Object, error) {
616657
var (
617658
pysub Object

py/tests/string.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -944,5 +944,14 @@ def __index__(self):
944944
else:
945945
assert False, "TypeError not raised"
946946

947+
doc="count"
948+
assert 'hello world'.count('l') == 3
949+
assert 'hello world'.count('l', 3) == 2
950+
assert 'hello world'.count('l', 3, 10) == 2
951+
assert 'hello world'.count('l', 3, 100) == 2
952+
assert 'hello world'.count('l', 3, 5) == 1
953+
assert 'hello world'.count('l', 3, 1) == 0
954+
assert 'hello world'.count('z') == 0
955+
947956

948957
doc="finished"

0 commit comments

Comments
 (0)