Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#import <string>
@interface NSString (cpp)
- (NSUInteger)populateStdString:(std::string&)str
usingEncoding:(NSStringEncoding)encoding
range:(NSRange)range;
@end
@implementation NSString (cpp)
// Populate a std::string avoiding a double-copy
- (NSUInteger)populateStdString:(std::string&)str
usingEncoding:(NSStringEncoding)encoding
range:(NSRange)range {
NSUInteger estimatedSize = [self maximumLengthOfBytesUsingEncoding:encoding];
str.resize(estimatedSize);
char *pch = (char*)str.data();
NSUInteger usedBufferCount = 0;
[self getBytes:pch
maxLength:estimatedSize
usedLength:&usedBufferCount
encoding:encoding
options:0
range:range
remainingRange:NULL];
str.resize(usedBufferCount);
return usedBufferCount;
}
@end
std::string u8substr;
NSUInteger size = [nsstr populateStdString:u8substr
usingEncoding:NSUTF8StringEncoding
range:highlightRange];
BOOL u8substrIsMutlibyte = size != str.length;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.