Swift: Test boundary of String.Index for substring function

后端 未结 2 1376
野的像风
野的像风 2021-01-19 02:36

Wow. Swift makes it really fiddly to copy a substring from a simple String.

Most programming languages allow characters to be simply indexed by their intege

相关标签:
2条回答
  • 2021-01-19 02:54

    You can use

    let ind1 = str.startIndex.advancedBy(c1, limit: str.endIndex)
    let ind2 = str.startIndex.advancedBy(c1+c2, limit: str.endIndex)
    

    to advance the start index by the given amounts, but not beyond the end index of the string. With that modification, your function gives

    subStr ("Stack Overflow", c1: 6, c2: 12) // "Overflow"
    subStr ("Stack Overflow", c1: 12, c2: 20) // ""
    
    0 讨论(0)
  • 2021-01-19 03:00

    I quickly made a nice substring function for Strings without Foundation dependency:

    extension String {
        func substring(from: Int, length: Int) -> String {
            return String(dropFirst(from).prefix(length))
        }
    }
    

    If the length is bigger than possible, it just gives all the characters to the end. Can't crash Can't crash as long as neither argument is negative (it makes sense to crash if any argument is negative since that would be a major flaw in your code).

    Example usage:

    "Stack Overflow".substring(from: 6, length: 12)
    

    gives

    "Overflow"
    
    0 讨论(0)
提交回复
热议问题