将字符串数组连接到单个字符串中,从使用Swift的Array的特定索引开始

时间:2017-09-27 10:08:26

标签: arrays swift string swift3

所以我有全名文本字段,我通过按空格分割完整名称来创建nameComponents数组。现在我想将0索引元素作为名字,其余组件作为姓氏。我喜欢this在Swift中加入字符串数组的方法。有没有办法从特定索引(在我的情况下索引1)开始加入数组。我不想使用循环。

4 个答案:

答案 0 :(得分:2)

您可以使用Mockito mock of SecurityManager throwing an exceptiondropFirst()

<强> dropFirst()

 let names = "It is a long name".components(separatedBy: " ")
 let lastName = names.dropFirst(2).joined(separator: " ")        
 print(lastName)//a long name

<强> dropFirst(_:)

axios.get('../assets/json/ar/myfile.json')
    .then(response => {
      // JSON responses are automatically parsed.
      console.log(response)
    })
    .catch(e => {
      this.errors.push(e)
    })

答案 1 :(得分:1)

如果您只想在第一个空格中分隔字符串,则无需将字符串完全拆分为数组。 您可以找到第一个空格并直接确定其前后的部分。 示例(Swift 3):

let string = "foo bar baz"

if let range = string.range(of: " ") {
    let firstPart = string.substring(to: range.lowerBound)
    let remainingPart = string.substring(from: range.upperBound)

    print(firstPart)        // foo
    print(remainingPart)    // bar baz
}

在Swift 4中,您将使用

提取部件
    let firstPart = String(string[..<range.lowerBound])
    let remainingPart = String(string[range.upperBound...])

答案 2 :(得分:0)

尝试使用Swift3:

let array = ["zero", "one", "two", "three"]
let str = array[1..<array.count].joined(separator: "-")
// po str
// "one-two-three"

答案 3 :(得分:0)

对于这个问题,您可以这样做:

  1. 删除数组的第一个元素到您的变量;
  2. 现在,最后一部分是你的姓氏。
  3. 示例:

    var nameComponents = ["My", "name", "is"]
    
    let firstName = nameComponents.remove(at: 0) // "My"
    let lastName = nameComponents.joined(separator: " ") // "name is"
    

    但更实际的方法是使用array subscript by passing Range

    let firstName = nameComponents.first!
    
    // Swift 3
    let lastName = nameComponents[1..<nameComponents.count].joined(separator: " ")
    
    // Swift 4
    let lastName = nameComponents[1...].joined(separator: " ")
    
相关问题