2010-08-12 162 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]; 
}