IT TIP

주어진 횟수만큼 다른 문자열을 반복하여 NSString 만들기

itqueen 2020. 12. 26. 16:21
반응형

주어진 횟수만큼 다른 문자열을 반복하여 NSString 만들기


이것은 쉽지만 가장 쉬운 해결책을 찾는 데 어려움을 겪고 있습니다.

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"

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.


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

If you're using Cocoa in Python, then you can just do that, as PyObjC imbues NSString with all of the Python unicode class's abilities.

Otherwise, there are two ways.

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

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 NSMutableString and append the string to it n times, like this:

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.

Therefore, I recommend the componentsJoinedByString: solution.

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

ReferenceURL : https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times

반응형