2011-10-10 62 views
5

如何字符串轉換爲陣列中的目標C.即我有一個字符串,如何將字符串轉換爲目標C中的數組?

NSString *str = @"Hi,How r u"; 

這應被轉換成一個數組*的NSMutableArray ARR,其中在

ARR [0 ] = 「您好」
ARR [1] = 「」
ARR [2] = 「如何」
ARR [3] = 「R」
ARR [4] = 「U」

任何人都可以幫助解決這個問題的想法。

回答

11
NSString *[email protected]"Hi,How r u"; 
NSArray *arr = [str componentsSeparatedByString:@","]; 
NSString *strSecond = [arr objectAtIndex:1]; 

NSMutableArray *arrSecond = [strSecond componentsSeparatedByString:@" "]; 
NSString *strHow = [arr objectAtIndex:0]; 
NSString *strAre = [arr objectAtIndex:1]; 
NSString *strYou = [arr objectAtIndex:2]; 

[arr removeObjectAtIndex:1]; 
[arr addObject:@","]; 
[arr addObject:strHow]; 
[arr addObject:strAre]; 
[arr addObject:strYou]; 

ARR是所需的陣列。

0

您可以使用NSString方法componentsSeparatedByString。看看參考here

+0

我需要逗號(,)也存儲在數組中。在這種情況下,我不能使用componentsSeparatedByString。 – shasha

5

我想this link會幫助你。

NSString *str = @"Hi,How r u"; 
NSArray *listItems = [str componentsSeparatedByString:@","]; 
1

試試這個

NSString *[email protected]"Hi,How r u"; 
    NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]]]; 
    NSLog(@"%@",arary); 

,如果你想,作爲一個對象

NSString *[email protected]"Hi,How r u"; 
    str2 = [str2 stringByReplacingOccurrencesOfString:@"," withString:@" , "]; 
    NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByString:@" "]]; 
    NSLog(@"%@",arary); 
3

你要做的,

NSString *str = @"Hi,How r u"; 
NSArray *arr = [str componentsSeparatedByString:@" "]; 

而且,爲了使這個像您期望的工作,應該有"Hi,""How"之間的white-space。你的字符串應該看起來像@"Hi, How r u"

相關問題