1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

string: add repeat() method

This commit is contained in:
Don Alfons Nisnoni 2019-09-27 03:54:53 +08:00 committed by Alexander Medvednikov
parent 9834ccfcd9
commit fb4f14ba76
2 changed files with 19 additions and 0 deletions

View File

@ -1009,3 +1009,17 @@ pub fn (s string) bytes() []byte {
C.memcpy(buf.data, s.str, s.len)
return buf
}
// Returns a new string with a specified number of copies of the string it was called on.
pub fn (s string) repeat(count int) string {
if count <= 1 {
return s
}
ret := malloc(s.len * count + count)
C.strcpy(ret, s.str)
for count > 1 {
C.strcat(ret, s.str)
count--
}
return string(ret)
}

View File

@ -459,3 +459,8 @@ fn test_ustring_count() {
assert (a.count(''.ustring())) == 2
assert (a.count('a'.ustring())) == 0
}
fn test_repeat() {
s := 'V! '
assert s.repeat(5) == 'V! V! V! V! V! '
}