ios - 在 iOS 中获取字符串中空格后的字符

标签 ios objective-c xcode

我有一个这样的字符串:@"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/

相关文章:

iphone - 如何将特定 View 的方向更改为横向?

objective-c - 界面生成器中导航 Controller 的导航项

ios - Agora SDK 视频不工作,甚至本地视频不显示在 swift

ios - 如何快速添加 subview Controller ?

javascript - iPhone 方向 HTML 隐藏

ios - Xcode 在点击时禁用 UIButton 标题淡入淡出

ios - 如何在共享扩展中集成 Fabric/Crashlytics

ios - 使用 AVAudioEngine 离线渲染音频文件

objective-c - 当 "Title Bar"设置为不显示时,为什么我无法在 NSPanel 中获得焦点?

ios - mediaTypesRequiringUserActionForPlayback 无法工作 Swift