In Objective-C, how to print out N spaces? (using stringWithCharacters)

天涯浪子 提交于 2019-12-05 02:49:56

You can use %*s to specify the width.

NSLog(@"Hello%*sWorld", 12, "");

Reference:

A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision. Applications shall ensure that arguments specifying field width, or precision, or both appear in that order before the argument, if any, to be converted.

trudyscousin

This will get you what you want:

NSLog(@"hello%@world", [@"" stringByPaddingToLength:12 withString:@" " startingAtIndex:0]);

I think the issue you have is you are misinterpreting what +(NSString *)stringWithCharacters:length: is supposed to do. It's not supposed to repeat the characters, but instead copy them from the array into a string.

So in your case you only have a single ' ' in the array, meaning the other 11 characters will be taken from whatever follows arrayChars in memory.

If you want to print out a pattern of n spaces, the easiest way to do that would be to use -(NSString *)stringByPaddingToLength:withString:startingAtIndex:, i.e creating something like this.

NSString *formatString = @"Hello%@World";
NSString *paddingString = [[NSString string] stringByPaddingToLength: n withString: @" " startingAtIndex: 0];
NSLog(formatString, paddingString);

This is probably the fastest method:

NSString *spacesWithLength(int nSpaces)
{
    char UTF8Arr[nSpaces + 1];

    memset(UTF8Arr, ' ', nSpaces * sizeof(*UTF8Arr));
    UTF8Arr[nSpaces] = '\0';

    return [NSString stringWithUTF8String:UTF8Arr];
}

The reason your current code isn't working is because +stringWithCharacters: expects an array with a length of characters of 12, while your array is only 1 character in length {' '}. So, to fix, you must create a buffer for your array (in this case, we use a char array, not a unichar, because we can easily memset a char array, but not a unichar array).

The method I provided above is probably the fastest that is possible with a dynamic length. If you are willing to use GCC extensions, and you have a fixed size array of spaces you need, you can do this:

NSString *spacesWithLength7()
{
    unichar characters[] = { [0 ... 7] = ' ' };
    return [NSString stringWithCharacters:characters length:7];
}

Unfortunately, that extension doesn't work with variables, so it must be a constant.

Through the magic of GCC extensions and preprocessor macros, I give you.... THE REPEATENATOR! Simply pass in a string (or a char), and it will do the rest! Buy now, costs you only $19.95, operators are standing by! (Based on the idea suggested by @JeremyL)

// step 1: determine if char is a char or string, or NSString.
// step 2: repeat that char or string
// step 3: return that as a NSString
#define repeat(inp, cnt) __rep_func__(@encode(typeof(inp)), inp, cnt) 

// arg list: (int siz, int / char *input, int n)
static inline NSString *__rep_func__(char *typ, ...)
{
    const char *str = NULL;
    int n;

    {
        va_list args;
        va_start(args, typ);

        if (typ[0] == 'i')
            str = (const char []) { va_arg(args, int), '\0' };
        else if (typ[0] == '@')
            str = [va_arg(args, id) UTF8String];
        else
            str = va_arg(args, const char *);

        n = va_arg(args, int);

        va_end(args);
    }

    int len = strlen(str);
    char outbuf[(len * n) + 1];

    // now copy the content
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < len; j++) {
            outbuf[(i * len) + j] = str[j];
        }
    }

    outbuf[(len * n)] = '\0';
    return [NSString stringWithUTF8String:outbuf];
}

The stringWithCharaters:length: method makes an NSString (or an instance of a subclass of NSString) using the first length characters in the C array. It does not iterate over the given array of characters until it reaches the length.

The output you are seeing is the area of memory 12 Unicode characters long starting at the location of your passed 1 Unicode character array.

This should work.

NSLog(@"hello%@world", [NSString stringWithCharacters:"            " length:12]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!