Swift: How to get substring from start to last index of character

前端 未结 22 814
感情败类
感情败类 2020-11-30 19:09

I want to learn the best/simplest way to turn a string into another string but with only a subset, starting at the beginning and going to the last index of a character.

22条回答
  •  萌比男神i
    2020-11-30 19:48

    Here's an easy and short way to get a substring if you know the index:

    let s = "www.stackoverflow.com"
    let result = String(s.characters.prefix(17)) // "www.stackoverflow"
    

    It won't crash the app if your index exceeds string's length:

    let s = "short"
    let result = String(s.characters.prefix(17)) // "short"
    

    Both examples are Swift 3 ready.

提交回复
热议问题