Create NSString by repeating another string a given number of times

后端 未结 5 864
既然无缘
既然无缘 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:32

    The first method above is for a single character. This one is for a string of characters. It could be used for a single character too but has more overhead.

    + (NSString*)stringWithRepeatString:(char*)characters times:(unsigned int)repetitions;
    {
        unsigned int stringLength = strlen(characters);
        unsigned int repeatStringLength = stringLength * repetitions + 1;
    
        char repeatString[repeatStringLength];
    
        for (unsigned int i = 0; i < repetitions; i++) {
            unsigned int pointerPosition = i * repetitions;
            memcpy(repeatString + pointerPosition, characters, stringLength);       
        }
    
        // Set terminating null
        repeatString[repeatStringLength - 1] = 0;
    
        return [NSString stringWithCString:repeatString];
    }
    

提交回复
热议问题