我有一个这样的字符串:@"The Happy Day"
并且我只想将 "THD"
保存在另一个字符串中。我该怎么做?
最佳答案
我会这样做...
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 中那样的任何内置方法。
关于ios - 在 iOS 中获取字符串中空格后的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32282148/