Category talk:Wren-str: Difference between revisions
Content added Content deleted
(→Source code: Added more versatile Str.replace and minor edit to Str.exchange method.) |
(→Source code: Made Str.lshift/rshift methods more general.) |
||
Line 244: | Line 244: | ||
} |
} |
||
// Performs a circular shift of the characters of 's' |
// Performs a circular shift of the characters of 's' 'n' places to the left. |
||
// If 'n' is negative performs a circular right shift by '-n' places instead. |
|||
static lshift(s) { |
static lshift(s, n) { |
||
if (!(s is String)) s = "%(s)" |
if (!(s is String)) s = "%(s)" |
||
if (!(n is Num) || !n.isInteger) Fiber.abort("'n' must be an integer.") |
|||
var chars = s.toList |
var chars = s.toList |
||
var count = chars.count |
var count = chars.count |
||
if (count < 2) return s |
if (count < 2) return s |
||
if (n < 0) return rshift(s, -n) |
|||
n = n % count |
|||
if (n == 0) return s |
|||
for (i in 1..n) { |
|||
var t = chars[0] |
|||
for (j in 0..count-2) chars[j] = chars[j+1] |
|||
chars[-1] = t |
|||
} |
|||
return (count < 1000) ? Strs.concat_(chars) : Strs.concat(chars, 1000) |
return (count < 1000) ? Strs.concat_(chars) : Strs.concat(chars, 1000) |
||
} |
} |
||
// Performs a circular shift of the characters of 's' |
// Performs a circular shift of the characters of 's' 'n' places to the right. |
||
// If 'n' is negative performs a circular left shift by '-n' places instead. |
|||
static rshift(s) { |
static rshift(s, n) { |
||
if (!(s is String)) s = "%(s)" |
if (!(s is String)) s = "%(s)" |
||
if (!(n is Num) || !n.isInteger) Fiber.abort("'n' must be an integer.") |
|||
var chars = s.toList |
var chars = s.toList |
||
var count = chars.count |
var count = chars.count |
||
if (count < 2) return s |
if (count < 2) return s |
||
if (n < 0) return lshift(s, -n) |
|||
n = n % count |
|||
if (n == 0) return s |
|||
for (i in 1..n) { |
|||
var t = chars[-1] |
|||
for (j in count-2..0) chars[j+1] = chars[j] |
|||
chars[0] = t |
|||
} |
|||
return (count < 1000) ? Strs.concat_(chars) : Strs.concat(chars, 1000) |
return (count < 1000) ? Strs.concat_(chars) : Strs.concat(chars, 1000) |
||
} |
} |
||
// Convenience versions of the above methods which shift by just 1 place. |
|||
static lshift(s) { lshift(s, 1) } |
|||
static rshift(s) { rshift(s, 1) } |
|||
/* The indices (or ranges thereof) for all the following functions are measured in codepoints |
/* The indices (or ranges thereof) for all the following functions are measured in codepoints |