在iOS

时间:2015-08-29 02:31:01

标签: ios objective-c xcode

我有一个这样的字符串:@"The Happy Day"我想在另一个字符串中只保存"THD"。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我会这样做......

NSString *string = @"The  Happy Day";

// Create array of words in string...
NSArray *words = [string componentsSeparatedByString:@" "];

// Create array to hold first letter of each word...
NSMutableArray *firstLetters = [NSMutableArray arrayWithCapacity:[words count]];

// Iterate through words and add first letter of each word to firstLetters array...
for (NSString *word in words) {
    if ([word length] == 0) continue;
    [firstLetters addObject:[word substringToIndex:1]];
}

// Join the first letter error into a single string...
NSString *acronym = [firstLetters componentsJoinedByString:@""];

使用Swift中的函数类型(例如map)可以做得更好,但是在Objective-C中没有任何类似的内置方法。

答案 1 :(得分:0)

NSString *str = @"The Happy Day";

NSMutableString *result = [NSMutableString string];
[[str componentsSeparatedByString:@" "] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if(obj){
            [result appendString:[((NSString *)obj) substringToIndex:1]];
        }

 }];