objective-c 通过将另一个字符串重复给定次数来创建 NSString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/260945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:53:44  来源:igfitidea点击:

Create NSString by repeating another string a given number of times

objective-ccocoastring

提问by Sergio Acosta

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

这应该很容易,但我很难找到最简单的解决方案。

I need an NSStringthat is equal to another string concatenated with itself a given number of times.

我需要一个NSString等于另一个字符串与自身连接给定次数的字符串。

For a better explanation, consider the following python example:

为了更好地解释,请考虑以下 python 示例:

>> original = "abc"
"abc"
>> times = 2
2
>> result = original * times
"abcabc"

Any hints?

任何提示?



EDIT:

编辑:

I was going to post a solution similar to the one by Mike McMaster's answer, after looking at this implementation from the OmniFrameworks:

在查看了 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];
}

Code reproduced from the file:

从文件中复制的代码:

Frameworks/OmniFoundation/OpenStepExtensions.subproj/NSString-OFExtensions.m

on the OpenExtensions framework from the Omni Frameworksby The Omni Group.

从该OpenExtensions框架全框架奥姆尼集团

回答by tig

There is a method called stringByPaddingToLength:withString:startingAtIndex::

有一种方法叫做stringByPaddingToLength:withString:startingAtIndex:

[@"" stringByPaddingToLength:100 withString: @"abc" startingAtIndex:0]

Note that if you want 3 abc's, than use 9 (3 * [@"abc" length]) or create category like this:

请注意,如果您想要 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

回答by Mike McMaster

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"

回答by Mike McMaster

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

为了性能,您可以使用以下内容进入 C:

+ (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.

这可以写成 NSString 类的类别扩展。可能有一些检查应该放在那里,但这是它的直接要点。

回答by Mike McMaster

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];
}

回答by Peter Hosey

If you're using Cocoa in Python, then you can just do that, as PyObjC imbues NSStringwith all of the Python unicodeclass's abilities.

如果您在 Python 中使用 Cocoa,那么您可以这样做,因为 PyObjC 充满NSString了 Pythonunicode类的所有功能。

Otherwise, there are two ways.

否则,有两种方法。

One is to create an array with the same string in it ntimes, and use componentsJoinedByString:. Something like this:

一种是创建一个数组,其中包含相同的字符串n,并使用componentsJoinedByString:. 像这样的东西:

NSMutableArray *repetitions = [NSMutableArray arrayWithCapacity:n];
for (NSUInteger i = 0UL; i < n; ++i)
    [repetitions addObject:inputString];
outputString = [repetitions componentsJoinedByString:@""];

The other way would be to start with an empty NSMutableStringand append the string to it ntimes, like this:

另一种方法是从一个空开始NSMutableString并将字符串附加到它的n时间,如下所示:

NSMutableString *temp = [NSMutableString stringWithCapacity:[inputString length] * n];
for (NSUInteger i = 0UL; i < n; ++i)
    [temp appendString:inputString];
outputString = [NSString stringWithString:temp];

You may be able to cut out the stringWithString:call if it's OK for you to return a mutable string here. Otherwise, you probably should return an immutable string, and the stringWithString:message here means you have two copies of the string in memory.

如果您可以在stringWithString:此处返回可变字符串,则您可以取消调用。否则,您可能应该返回一个不可变的字符串,stringWithString:这里的消息意味着您在内存中有该字符串的两个副本。

Therefore, I recommend the componentsJoinedByString:solution.

因此,我推荐该componentsJoinedByString:解决方案。

[Edit: Borrowed idea to use …WithCapacity:methods from Mike McMaster's answer.]

[编辑:借用Mike McMaster 回答中的…WithCapacity:方法的想法。]