简体   繁体   中英

unichar* to NSString, get the length

I am trying to create an NSString object from a const unichar buffer where I don't know the length of the buffer.

I want to use the NSString stringWithCharacters: length: method to create the string (this seems to work), but please can you help me find out the length?

I have:

const unichar *c_emAdd = [... returns successfully from a C++ function...]

NSString *emAdd = [NSString stringWithCharacters:c_emAdd length = unicharLen];

Can anyone help me find out how to check what unicharLen is? I don't get this length passed back to me by the call to the C++ function, so I presume I'd need to iterate until I find a terminating character? Anyone have a code snippet to help? Thanks!

Is your char buffer null terminated? Is it 16-bit unicode?

NSString *emAdd = [NSString stringWithFormat:@"%S", c_emAdd];

Your unichar s should be null terminated so you when you reach two null bytes (a unichar = 0x0000) in the pointer you will know the length.

unsigned long long unistrlen(unichar *chars)
{
    unsigned long long length = 0llu;
    if(NULL == chars) return length;

    while(NULL != chars[length])
        length++;

    return length;
}

    //...
    //Inside Some method or function
    unichar chars[] = { 0x005A, 0x0065, 0x0062, 0x0072, 0x0061, 0x0000 };

    NSString *string = [NSString stringWithCharacters:chars length:unistrlen(chars)];

    NSLog(@"%@", string);

Or even simpler format with %S specifier

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