【问题标题】:How to create an array of separate strings from a string如何从字符串创建一个单独的字符串数组
【发布时间】:2019-09-04 10:40:27
【问题描述】:

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

"One two three four"

我怎样才能将它拆分成这样的数组:

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

【问题讨论】:

  • 如果您在发布问题之前进行一些研究并包括您尝试过的内容,而不是仅仅将 stackoverflow 视为某种免费的代码编写服务,我们将不胜感激。

标签: arrays swift string


【解决方案1】:

你可以试试

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)

【讨论】:

  • 这行得通——但我对问题进行了编辑,所以输出不同——你能检查一下吗?
  • 类似:let str = "One two three four".split(separator: " "); let res = str.indices.map { str.suffix($0 + 1).joined(separator: " ") }
【解决方案2】:

您可以使用String.components(separatedBy:)String 拆分为单词,然后使用mapArray 的索引上获取其第一个n 元素,使用prefix(through:)joined(separator:) 加入个人串成一个。

let stringWithWords = "One two three four"
let words = stringWithWords.components(separatedBy: " ")
let wordsArray = words.indices.map({words.prefix(through: $0).joined(separator: " ")})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多