I have a somewhat long string (around 2.000 characters, but could be more) which I need to break into parts of up to 255 byte chunks. I realize I have to iterate over the whole string (saw it here), but it's not clear how.
How can I do this?
I have a somewhat long string (around 2.000 characters, but could be more) which I need to break into parts of up to 255 byte chunks. I realize I have to iterate over the whole string (saw it here), but it's not clear how.
How can I do this?
IF you look at The Swift Programming Guide
from page 128 you can see how to iterate over a string. The bytes that you get from the string do depend on the encoding that you ask the string to give to you. You probably want UTF-8 (an 8 bit encoding) which is described on page 130:
let dogString = "Dog!"
for codeUnit in dogString {
print("\(codeUnit) ")
}”
“print("\n")
// 68 111 103 33 240 159 144 182”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l
Note 1 code unit may not contain the whole of a character (as some characters are represented by multiple code units, in this case the 'dogface' has a 4 byte encoding, whereas the ascii characters require only one byte each).
NSString *str = [NSString stringWithContentsOfFile:[@"~/Desktop/bytes" stringByExpandingTildeInPath] encoding:NSUTF8StringEncoding error:nil];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *chunks = [NSMutableArray array];
NSUInteger readPointer = 0;
NSUInteger distanceToEndOfData;
while (readPointer + 255 < data.length) {
distanceToEndOfData = data.length - readPointer;
[chunks addObject:[data subdataWithRange:NSMakeRange(readPointer, 255)]];
readPointer += 255;
}
distanceToEndOfData = data.length - readPointer;
if (distanceToEndOfData > 0) [chunks addObject:[data subdataWithRange:NSMakeRange(readPointer, distanceToEndOfData)]];
NSLog(@"%@", chunks);
Let me know if you want an explanation of the code.