Sunday, May 12, 2013

NSString stringWithCharacters length example ios


stringWithCharacters: length:

Returns a string containing a given number of characters taken from a given C array of Unicode characters.
+ (id)stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
Parameters
chars
A C array of Unicode characters; the value must not be NULL.

Important: Raises an exception if chars is NULL, even if length is 0.
length
The number of characters to use from chars.
Return Value
A string containing length Unicode characters taken (starting with the first) from chars.
[ NSString stringWithCharacters length example ]
NSString *spacesWithLength7()
{
    unichar characters[] = { [0 ... 7] = ' ' };
    return [NSString stringWithCharacters:characters length:7];
}
[ NSString stringWithCharacters length example ]
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);
[ NSString stringWithCharacters length example ]
NSString *sentence = @"A long unicode sentence";

NSUInteger length = [sentence length];
unichar aBuffer[length + 1];

[sentence getCharacters:aBuffer range:NSMakeRange(0, length)];
aBuffer[length] = 0x0;

NSString *newStr = [NSString stringWithCharacters:aBuffer length:length];

NSLog(@"%@", newStr);