Sometimes you might want to receive the contents of a CFString not as an entire block of characters but one Unicode character at a time. Perhaps you might be looking for a particular character or sequence of characters, such as special control characters indicating the start and end of a "record." String Services gives you three ways to process Unicode characters.
The first way is to use the
CFStringGetCharacters
function described in Getting the Contents as Unicode Strings to copy the characters to a local buffer and then cycle through the characters in the buffer. But this technique can be expensive memory-wise, especially if a large number of characters is involved.
The second way to access characters one at a time is to use the
CFStringGetCharacterAtIndex
function, as Listing 9 illustrates.
Listing 9 Getting a character at a time
CFIndex length, i; UniChar uchar; CFStringRef str; str = CFStringCreateWithCString(NULL, "Hello World", CFStringGetSystemEncoding()); length = CFStringGetLength(str); for (i=0; i < length; i++) { uchar = CFStringGetCharacterAtIndex(str, i); // Process character.... }
Although this function does not require a large chunk of memory to hold a block of characters, it can be slow, especially if there are a lot of characters to process.
The third technique for character processing, exemplified in Listing 10, combines the convenience of one-at-a-time character access with the efficiency of bulk access. The in-line functions
CFStringInitInlineBuffer
and
CFStringGetCharacterFromInlineBuffer
give fast access to the contents of a string when you are doing sequential character processing. To use this programming interface, call the
CFStringInitInlineBuffer
function with a
CFStringInlineBuffer
structure (on the stack, typically) and a range of the CFString's characters. Then call
CFStringGetCharacterFromInlineBuffer
as many times as you want using an index into that range relative to the start of the range. Because these are in-line functions they access the CFString object only periodically to fill the in-line buffer.
Listing 10 Processing characters in an in-line buffer
CFStringRef str; CFStringInlineBuffer inlineBuffer; CFIndex length; CFIndex cnt; str = CFStringCreateWithCString(NULL, "Hello World", CFStringGetSystemEncoding()); length = CFStringGetLength(str) CFStringInitInlineBuffer(str, &inlineBuffer, CFRangeMake(0, length)); for (cnt = 0; cnt < length; cnt++) { UniChar ch = CFStringGetCharacterFromInlineBuffer(&inlineBuffer, cnt); // Process character... }