| 1 |
/* |
| 2 |
https://github.com/Zxilly/playground-cj/blob/master/src/examples/functional.cj |
| 3 |
*/ |
| 4 |
package playground |
| 5 |
|
| 6 |
// 用给定的分隔符拆分字符串,支持多分隔符 |
| 7 |
import std.collection.* |
| 8 |
|
| 9 |
// 常规实现 |
| 10 |
func split_normal(text: String, sep: String): ArrayList<String> { |
| 11 |
let indices = ArrayList<Int64>() |
| 12 |
var last = true |
| 13 |
for (i in 0..text.size) { |
| 14 |
let current = sep.indexOf(text[i]).isSome() |
| 15 |
if (last != current) { |
| 16 |
indices.add(i) |
| 17 |
} |
| 18 |
last = current |
| 19 |
} |
| 20 |
if (!last) { |
| 21 |
indices.add(text.size) |
| 22 |
} |
| 23 |
|
| 24 |
let result = ArrayList<String>() |
| 25 |
for (i in 0..indices.size : 2) { |
| 26 |
result.add(text[indices[i]..indices[i + 1]]) |
| 27 |
} |
| 28 |
return result |
| 29 |
} |
| 30 |
|
| 31 |
// 函数式编程实现 |
| 32 |
func split(text: String, sep: String): ArrayList<String> { |
| 33 |
let indices = ArrayList<Int64>() |
| 34 |
text |> enumerate |> |
| 35 |
fold(false) { |
| 36 |
state, e => |
| 37 |
let current = sep.indexOf(e[1]).isNone() |
| 38 |
if (state != current) { |
| 39 |
indices.add(e[0]) |
| 40 |
} |
| 41 |
current |
| 42 |
} |> { |
| 43 |
valid: Bool => if (valid) { |
| 44 |
indices.add(text.size) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
let result = ArrayList<String>() |
| 49 |
for (i in 0..indices.size : 2) { |
| 50 |
result.add(text[indices[i]..indices[i + 1]]) |
| 51 |
} |
| 52 |
return result |
| 53 |
} |
| 54 |
|
| 55 |
main() { |
| 56 |
let text = "123, 456 7&89, , 96^3, 567" |
| 57 |
let separator = "&^, " |
| 58 |
println(split_normal(text, separator)) |
| 59 |
println(split(text, separator)) |
| 60 |
} |