Cela devrait être facile, mais j'ai du mal à trouver la solution la plus simple.Créer NSString en répétant une autre chaîne un certain nombre de fois
J'ai besoin d'un NSString
qui est égal à une autre chaîne concaténée avec elle-même un certain nombre de fois.
Pour une meilleure explication, considérons l'exemple python suivant:
>> original = "abc"
"abc"
>> times = 2
2
>> result = original * times
"abcabc"
Tous les conseils?
EDIT:
je vais poster une solution similaire à celle par Mike McMaster's answer, après avoir examiné cette mise en œuvre des OmniFrameworks:
// 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 reproduit à partir du fichier:
Frameworks/OmniFoundation/OpenStepExtensions.subproj/NSString-OFExtensions.m
sur le framework OpenExtensions à partir du Omni Frameworks par The Omni Group.
+1 pour tout faire en un seul appel à la bibliothèque standard. Et voici comment je l'ai utilisé pour créer une liste de points d'interrogation séparés par des virgules (pour alimenter SQLite) - '[@" "stringByPaddingToLength: [fields count] * 2-1 avecString: @" ?, "startingAtIndex: 0] '. – noamtm