首页 > 解决方案 > 如何从字符串创建一个单独的字符串数组

问题描述

这在标题中很难解释,但我有一个这样的字符串:

"One two three four"

如何拆分它,使其产生如下数组:

["four", "three four", "two three four", "one two three four"]

标签: arraysswiftstring

解决方案


你可以试试

let str = "One two three four".components(separatedBy: " ")  
let res = str.indices.map { str[0...$0].joined(separator: " ") } 
print(res)

let str = Array("One two three four".components(separatedBy: " ").reversed())
let res = str.indices.map { str[0...$0].reversed().joined(separator: " ") }
print(res)

推荐阅读