-3

I have a 512 character long string, from which I need to print 16 character long sections, in a loop.

For example, characters 1-16, then 2-17, then 3-18 etc.

The only way I can find to print a substring is to use substringWithRange to generate the substring I want. But this allocates a new string every time, which hits the heap and is causing me poor performance.

How can I print a substring without creating a new string?

Ian Partridge
  • 79
  • 1
  • 6
  • If it is in a loop then isn't it just re-assigning the same variable to the new substring? So in every iteration you are just assigning one variable. Unless I misinterpreted your description, I don't think that should cause a major performance issue. – amallard Feb 17 '16 at 17:02
  • Possible duplicate of [Get nth character of a string in Swift programming language](http://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language) – xoudini Feb 17 '16 at 17:03
  • 6
    "But this allocates a new string every time, which hits the heap and is causing me poor performance." Prove it. – matt Feb 17 '16 at 17:03

1 Answers1

2

Create an extension for subscripting ranges in strings:

extension String {

    subscript (i: Int) -> Character {
        return self[self.startIndex.advancedBy(i)]
    }

    subscript (i: Int) -> String {
        return String(self[i] as Character)
    }

    subscript (r: Range<Int>) -> String {
        let start = startIndex.advancedBy(r.startIndex)
        let end = start.advancedBy(r.endIndex - r.startIndex)
        //return self[Range(start: start, end: end)] // Deprecated in Swift 2.x
        return self[Range(start ..< end)]            // Swift 3
    }
}

Credit to aleclarson, the author of this answer.


Then, if you need to print the string in 16-character chunks, do something along the lines of:

var start = 0
var end = 15

while end < 512 {
    print(yourString[start...end])
    start += 16
    end += 16
}

Though I'd recommending checking if the string is actually 512 characters long with yourString.characters.count, or simply setting the maximum index to the character count of the string.

Community
  • 1
  • 1
xoudini
  • 7,001
  • 5
  • 23
  • 37
  • That doesn't work: `String` is not subscriptable by `Range` – vadian Feb 17 '16 at 17:23
  • See the answer I linked. (Fixed so that the hyperlink now goes directly to the answer I meant) – xoudini Feb 17 '16 at 17:31
  • It looks like the code of another answer is necessary for your answer. You can copy (all of / part of) this other answer in yours (based on the idea that "an answer should be able to stand on its own"). The only condition is to give proper attribution to the other author and have a link to it (but I see you already have the link). Just a suggestion, of course. Thanks. – Eric Aya Feb 17 '16 at 17:54