2010-08-12 159 views
16

我有一個字符串的文本如下所示分割一個字符串轉換成不同的字符串

011597464952,01521545545,454545474,454545444|Hello this is were the message is. 

基本上我希望每個在不同串的數字到消息例如

NSString *Number1 = 011597464952 
NSString *Number2 = 01521545545 
etc 
etc 
NSString *Message = Hello this is were the message is. 

我將喜歡從一個包含它的字符串中拆分出來

回答

45

我會用-[NSString componentsSeparatedByString]

NSString *str = @"011597464952,01521545545,454545474,454545444|Hello this is were the message is."; 

NSArray *firstSplit = [str componentsSeparatedByString:@"|"]; 
NSAssert(firstSplit.count == 2, @"Oops! Parsed string had more than one |, no message or no numbers."); 
NSString *msg = [firstSplit lastObject]; 
NSArray *numbers = [[firstSplit objectAtIndex:0] componentsSepratedByString:@","]; 

// print out the numbers (as strings) 
for(NSString *currentNumberString in numbers) { 
    NSLog(@"Number: %@", currentNumberString); 
} 
0

does objective-c have strtok()

strtok函數根據一組分隔符將字符串拆分爲子字符串。 每個後續調用都會給出下一個子字符串。

substr = strtok(original, ",|"); 
while (substr!=NULL) 
{ 
    output[i++]=substr; 
    substr=strtok(NULL, ",|") 
} 
+0

沒有,但是C確實,由於Objective-C的是C嚴格的超集, Objective-C可以免費獲得它。 – Allyn 2010-08-12 18:28:03

+0

你能解釋一下嗎:) – user393273 2010-08-12 18:30:36

+0

我不認爲這會對目標有效c – user393273 2010-08-12 18:39:32

5

看看NSStringcomponentsSeparatedByString或其中一個類似的API。

如果是這種結果的一個已知的固定集,然後你可以承擔由此產生的數組,並使用它像:

NSString *number1 = [array objectAtIndex:0];  
NSString *number2 = [array objectAtIndex:1]; 
... 

如果是可變的,看NSArray API和objectEnumerator選項。

+0

是的我發現早些時候,但我如何將每個數組放入一個單獨的字符串? – user393273 2010-08-12 18:33:16

+0

在原文中增加了一些細節。 – Eric 2010-08-12 18:50:49

1
NSMutableArray *strings = [[@"011597464952,01521545545,454545474,454545444|Hello this is were the message is." componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@",|"]] mutableCopy]; 

NString *message = [[strings lastObject] copy]; 
[strings removeLastObject]; 

// strings now contains just the number strings 
// do what you need to do strings and message 

.... 

[strings release]; 
[message release]; 
0

這裏有一個方便的功能,我使用:

///Return an ARRAY containing the exploded chunk of strings 
///@author: khayrattee 
///@uri: http://7php.com 
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter 
{ 
    return [stringToBeExploded componentsSeparatedByString: delimiter]; 
}