Category talk:Wren-str: Difference between revisions
Content added Content deleted
(Fixed minor bug in Greek.names property and added Str.splitNoEmpty method.) |
(→Source code: Added more versatile Str.replace and minor edit to Str.exchange method.) |
||
Line 368: | Line 368: | ||
if (i == j) return s |
if (i == j) return s |
||
var chars = s.toList |
var chars = s.toList |
||
chars.swap(i, j) |
|||
⚫ | |||
⚫ | |||
return Strs.concat(chars) |
return Strs.concat(chars) |
||
} |
} |
||
// Returns 's' with 'from' replaced by 'to' up to 'n' times (all times if n is negative) |
|||
// but skipping the first 'skip' matches. |
|||
static replace(s, from, to, n, skip) { |
|||
if (!(from is String)) Fiber.abort("'from 'must be a string.") |
|||
if (!(to is String)) Fiber.abort("'to' must be a string.") |
|||
if (!(n is Num && n.isInteger)) Fiber.abort("'n' must be an integer.") |
|||
if (!(skip is Num && skip.isInteger && skip >= 0)) { |
|||
Fiber.abort("'skip' must be a non-negative integer.") |
|||
} |
|||
if (!(s is String)) s = "%(s)" |
|||
if (n < 0) { |
|||
if (skip == 0) return s.replace(from, to) |
|||
n = Num.maxSafeInteger |
|||
} |
|||
if (n == 0 || skip >= n) return s |
|||
⚫ | |||
var split = s.split(from) |
|||
⚫ | |||
for (i in 0...split.count-1) { |
|||
count = count + 1 |
|||
res = res + split[i] + ((count <= skip || count > n) ? from : to) |
|||
} |
|||
return res + split[-1] |
|||
} |
|||
// Convenience version of 'replace' where 'skip' is always zero. |
|||
static replace(s, from, to, n) { replace(s, from, to, n, 0) } |
|||
// Returns 's' repeated 'reps' times. |
// Returns 's' repeated 'reps' times. |