Create NSString by repeating another string a given number of times

后端 未结 5 862
既然无缘
既然无缘 2020-12-08 00:02

This should be easy, but I\'m having a hard time finding the easiest solution.

I need an NSString that is equal to another string concatenated with itse

5条回答
  •  生来不讨喜
    2020-12-08 00:56

    For performance, you could drop into C with something like this:

    + (NSString*)stringWithRepeatCharacter:(char)character times:(unsigned int)repetitions;
    {
        char repeatString[repetitions + 1];
        memset(repeatString, character, repetitions);
    
        // Set terminating null
        repeatString[repetitions] = 0;
    
        return [NSString stringWithCString:repeatString];
    }
    

    This could be written as a category extension on the NSString class. There are probably some checks that should be thrown in there, but this is the straight forward gist of it.

提交回复
热议问题