这应该很简单,但我很难找到最简单的解决方案.
我需要一个NSString
等于另一个与自身连接一次的字符串.
有关更好的解释,请考虑以下python示例:
>> original = "abc" "abc" >> times = 2 2 >> result = original * times "abcabc"
任何提示?
编辑:
在看完OmniFrameworks的这个实现之后,我将发布一个类似Mike McMaster答案的解决方案:
// returns a string consisting of 'aLenght' spaces + (NSString *)spacesOfLength:(unsigned int)aLength; { static NSMutableString *spaces = nil; static NSLock *spacesLock; static unsigned int spacesLength; if (!spaces) { spaces = [@" " mutableCopy]; spacesLength = [spaces length]; spacesLock = [[NSLock alloc] init]; } if (spacesLength < aLength) { [spacesLock lock]; while (spacesLength < aLength) { [spaces appendString:spaces]; spacesLength += spacesLength; } [spacesLock unlock]; } return [spaces substringToIndex:aLength]; }
从文件中复制的代码:
Frameworks/OmniFoundation/OpenStepExtensions.subproj/NSString-OFExtensions.m
从该OpenExtensions框架全框架由奥姆尼集团.
有一种方法叫做stringByPaddingToLength:withString:startingAtIndex:
:
[@"" stringByPaddingToLength:100 withString: @"abc" startingAtIndex:0]
请注意,如果你想要3个abc,那么使用9(3 * [@"abc" length]
)或创建如下类别:
@interface NSString (Repeat) - (NSString *)repeatTimes:(NSUInteger)times; @end @implementation NSString (Repeat) - (NSString *)repeatTimes:(NSUInteger)times { return [@"" stringByPaddingToLength:times * [self length] withString:self startingAtIndex:0]; } @end
NSString *original = @"abc"; int times = 2; // Capacity does not limit the length, it's just an initial capacity NSMutableString *result = [NSMutableString stringWithCapacity:[original length] * times]; int i; for (i = 0; i < times; i++) [result appendString:original]; NSLog(@"result: %@", result); // prints "abcabc"