2012-07-03 49 views

回答

13
NSString* nameStr = @"Firstname Lastname"; 
NSArray* firstLastStrings = [nameStr componentsSeparatedByString:@" "]; 
NSString* firstName = [firstLastStrings objectAtIndex:0]; 
NSString* lastName = [firstLastStrings objectAtIndex:1]; 
char lastInitialChar = [lastName characterAtIndex:0]; 
NSString* newNameStr = [NSString stringWithFormat:@"%@ %c.", firstName, lastInitialChar]; 

的第一個字符這可能是簡潔得多,但我想清晰對於OP :)因此,所有的臨時變量和var名稱。

2

可以使用componentsSeparatedByString使用此代碼片段中,首先單獨字符串,然後再加入他們的行列,但只能得到Lastname

NSString *str = @"Firstname Lastname"; 
NSArray *arr = [str componentsSeparatedByString:@" "]; 
NSString *newString = [NSString stringWithFormat:@"%@ %@.", [arr objectAtIndex:0], [[arr objectAtIndex:1] substringToIndex:1]]; 
0

獲取名稱的部分數組分別:

NSString *sourceName = ...whatever...; 

NSArray *nameComponents = 
    [sourceName 
     componentsSeparatedByCharactersInSet: 
      [NSCharacterSet whitespaceCharacterSet]]; 

然後,我想:

NSString *compactName = 
    [NSString stringWithFormat:@"%@ %@.", 
     [nameComponents objectAtIndex:0], 
     [[nameComponents lastObject] substringToIndex:1]]; 

這將跳過任何中間名,但如果只有一個名稱,如說'傑弗裏',那麼它會輸出'傑弗裏J.'。如果您傳遞空字符串,那麼當您嘗試獲取objectAtIndex:0時,它會引發異常,因爲該數組將爲空。所以你應該檢查[nameComponents count]

4

這將做到這一點:

NSArray *components = [fullname componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
NSString *firstnameAndLastnameInitial = [NSString stringWithFormat:@"%@ %@.", [components objectAtIndex:0], [[components objectAtIndex:1] substringToIndex:1]]; 

這假定全名是的NSString的實例,幷包含由空格分隔兩個部分組成,所以你需要檢查這一點。

相關問題