2015-08-29 55 views
3

我有這樣一個字符串:@"The Happy Day",我想只在另一個字符串中保存"THD"。我怎樣才能做到這一點?獲取字符串中的空白後的字符在iOS中

+0

你是否特意試圖捕捉第一個字母或首都? 「活動日」是否應歸還「TAD」,「ThD」或「THD」? – nbering

+0

對不起,在我的問題後讀了標題。什麼語言?你有一個命名的操作系統和開發環境,但這可能是Objective-C或Swift。 – nbering

+0

Hi Bro,我的意思是應該「hAppy Day」返回「ThD」和Objective-C語言。謝謝bro –

回答

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:@""]; 

它可以使用雨燕的功能類型,如map做要好得多,但也有不一樣,在任何目的內置方法-C。

+0

謝謝,它對我很有幫助 –

+0

@DongNguyen它應該使用特定的字符串,但我已經修改了我的答案,以便它跳過空的單詞 - 這可能發生如果一行中有兩個空格或一個任何情況下都應該解決你遇到的問題。 – Robert

+0

嗨,兄弟,謝謝你,我修好了。 –

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]]; 
     } 

}]; 
+0

它有用(y) –