简体   繁体   中英

How do I count the occurrences of a byte in NSData on an iphone?

I'm new to iOS and Objective C and I'm having trouble figuring out how to use NSData correctly.

I want to count the number of new lines in my data.

// filedata is pulled from a URL asyn

NSInteger knt = 0;
NSInteger len = filedata.length;
const char *pointer = [filedata bytes];

for (NSInteger spot = 0; spot < len; spot++) {
    if (pointer[spot] == 10) { // 10 is new line
        knt++;
    }
}

The count is off, is there a better way to do this?

Try checking for carriage returns as well (ascii 13 http://www.asciitable.com/ ).

Make sure the newlines are TRULY newlines (ascii 10). You can try this by opening up your data in a hex editor. Hex editors generally will show you text in a right pane, bytes in a middle pain, and addresses of the bytes in a left pane.

If this doesn't resolve your question, please consider posting sample data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM