Supposons que j’ai une chaîne comme celle-ci:
hello world this may have lots of sp:ace or little space
Je voudrais séparer cette chaîne à ceci:
@"hello", @"world", @"this", @"may", @"have", @"lots", @"of", @"sp:ace", @"or", @"little", @"space"
Je vous remercie.
NSSsortingng *aSsortingng = @"hello world this may have lots of sp:ace or little space"; NSArray *array = [aSsortingng componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];
tapé dans cette forme non testé
Je suggère une approche en deux étapes:
NSArray *wordsAndEmptySsortingngs = [yourLongSsortingng componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSArray *words = [wordsAndEmptySsortingngs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
Cela a fonctionné pour moi
NSSsortingng * str = @"Hi Hello How Are You ?"; NSArray * arr = [str componentsSeparatedBySsortingng:@" "]; NSLog(@"Array values are : %@",arr);
Il est très facile de faire cela avec des blocs, essayez quelque chose comme ceci:
NSSsortingng* s = @"hello world this may have lots of space or little space"; NSMutableArray* ar = [NSMutableArray array]; [s enumerateSubssortingngsInRange:NSMakeRange(0, [s length]) options:NSSsortingngEnumerationByWords usingBlock:^(NSSsortingng* word, NSRange wordRange, NSRange enclosingRange, BOOL* stop){ [ar addObject:word]; }];
NSSsortingng * mainSsortingng = @"Today is your day"; NSArray * array = [mainSsortingng componentsSeparatedBySsortingng:@" "]; NSLog(@"Expected ssortingng is : %@",array);