将一个字符串分割成不同的字符串

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.

我想把包含它的一个字符串分割出来。

5个回答

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);
}

5

请查看NSString componentsSeparatedByString或类似的API。

如果这是一个已知的固定结果集,您可以使用生成的数组进行以下操作:

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

如果是变量,可以查看NSArray API和objectEnumerator选项。

是的,我之前找到了,但是如何将每个数组放入单独的字符串中呢? - user393273
在原帖中添加了一些更详细的内容。 - Eric

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

Objective-C 有 strtok() 吗?

strtok 函数根据一组分隔符将字符串分割成子字符串。每次调用都会给出下一个子字符串。

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

不,但是C语言支持,由于Objective-C是C语言的严格超集,因此Objective-C可以免费获得该功能。 - Allyn
2
你可以在Objective-C中使用strtok(它是C的超集),但是strtok期望的是C风格的字符串。NSString则完全不同,它是一个Unicode字符串。虽然你可以获得一个C风格的字符串(给定一个编码),但我不会选择这种方法。 - Barry Wark
可以这样做,但你必须使用C字符串。 - Allyn

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];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接