Swift: Test boundary of String.Index for substring function

后端 未结 2 1386
野的像风
野的像风 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) // ""
    

提交回复
热议问题