2011-08-19 61 views
0

我收到以下格式的字符串。iPhone:如何分隔字符串,如「ListName |定義|答案」

ListName|Definition|Answer 

以及如何要分開它喜歡:

String1 : ListName 

String2 : Definition 

String3 : Answer 

在這裏,這句話可以按值的變化deffer。

因此,在任何其他點,它可能就像Hey|Name|Bye

但是|總是在字符串中。

是否有可能在字符串中計數|

我該如何區分它?

+1

像這樣:http://stackoverflow.com/questions/259956/nsstring-tokenize-in-objective-c? –

+0

可以統計字符串中的'|'的數量嗎? – Devang

回答

2

可以單獨它想:

NSString *string = @"ListName|Definition|Answer"; 
NSArray *chunks = [string componentsSeparatedByString: @"|"]; 

現在你有一個像數組:

chunk[0] = ListName 
chunk[1] = Definition 
chunk[2] = Answer 

希望它可以幫助你....

1

構建您的輸入字符串

NSArray *strArray = [string componentsSeparatedByString: @"|"]; 

然後填寫所有從這個數組NSString的數組。

2

你正在尋找的方法是內置到NSString類中。該課程的文檔可以在here找到。

使用的方法是。

- (NSArray *)componentsSeparatedByString:(NSString *)separator 

//An example of this in action 
NSString *exampleString = @"Test|some|strings"; 

NSArray *separatedStrings = [exampleString componentsSeparatedByString:@"|"]; 

在這一點上,你可以做任何你將與陣列中的每個字符串喜歡諸如循環訪問,或訪問序列中的特定字符串。

我已經包含了迭代返回供參考的元素的示例。

//This for example is a nice use of the NSArray enumeration 
//Much easier than the standard for loop with multiple parameters 
for(NSString *aComponent in separatedStrings) { 
    NSLog(@"A piece is: %@", aComponent); 
    //Do something with each string 
} 
2

使用此:

NSArray *comps = [string componentsSeparatedByString: @"|"]; 
NSString *listName = [comps objectAtIndex:0]; 
NSString *definition = [comps objectAtIndex:1]; 
NSString *answer = [comps objectAtIndex:2]; 
+0

我覺得'NSString * answer = [comps objectAtIndex:3];''應該是'NSString * answer = [comps objectAtIndex:2];' :) –

+0

哎呀,感謝您的評論:) – akashivskyy

2

下面是整個代碼:

的NSArray *陣列= [字符串componentsSeparatedByString:@ 「|」];你可以使用NSMutableArray * mutableArray = [NSMutableArray arrayWithArray:array];

for(int i=0; i<[mutableArray count]; i++) 
{ 
    NSString *strData = [mutableArray objectAtIndex:i]; 
    NSLog(@"%@",strData); 
} 

乾杯。