let total = [| "1X2"; "3X4"; "5X6" |]
let oddEven = total
|> Array.map(fun x -> x.Split('X'))
我有一个字符串数组,在上面的示例中是完全的,我想将数组拆分为“X”,如上例中的oddEven,但我想返回2个字符串数组:
let odd = [| 1; 3; 5 |]
和let even = [| 2; 4; 6 |]
这可能是一项轻松的任务,但我现在无法理解。 任何帮助是极大的赞赏! 谢谢,
答案 0 :(得分:4)
您应该检查每个字符串是否可以分成两部分,然后解压缩结果:
let total = [| "1X2"; "3X4"; "5X6" |]
let odds, evens = total |> Array.map (fun x -> match x.Split('X') with
| [|odd; even|] -> odd, even
| _ -> failwith "Wrong input")
|> Array.unzip;;
答案 1 :(得分:2)
let evens, odds = total
|> (Array.map (fun x -> x.Split('X')))
|> Array.concat
|> Array.partition (fun s -> int s % 2 = 0)
编辑:正如John Palmer在评论中指出的那样,你可以使用Array.collect而不是map和concat:
let evens, odds = total
|> Array.collect (fun s -> s.Split('X'))
|> Array.partition (fun s -> int s % 2 = 0);;
答案 2 :(得分:0)
let odd =
oddEven |> Array.map (fun x -> x.[0])
let even =
oddEven |> Array.map (fun x -> x.[1])