我的文字字符串如下所示
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.
我想从一个包含所有
的字符串中分离出来答案 0 :(得分: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);
}
答案 1 :(得分:5)
查看NSString componentsSeparatedByString
或其中一个类似的API。
如果这是一组已知的固定结果,那么您可以使用结果数组并使用它:
NSString *number1 = [array objectAtIndex:0];
NSString *number2 = [array objectAtIndex:1];
...
如果它是可变的,请查看NSArray API和objectEnumerator
选项。
答案 2 :(得分: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];
答案 3 :(得分:0)
objective-c有strtok()
吗?
strtok函数根据一组分隔符将字符串拆分为子字符串。 每个后续调用都会给出下一个子字符串。
substr = strtok(original, ",|");
while (substr!=NULL)
{
output[i++]=substr;
substr=strtok(NULL, ",|")
}
答案 4 :(得分: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];
}