web-dev-qa-db-ja.com

1つの文字列を別の文字列に分割する

以下に示すような文字列のテキストがあります

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.

すべてを含む1つの文字列から分割してもらいたい

16
user393273

私は使うだろう -[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);
}
45
Barry Wark

NSStringcomponentsSeparatedByStringまたは同様のAPIの1つを見てください。

これが既知の固定結果セットである場合は、結果の配列を取得して、次のように使用できます。

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

可変の場合は、 NSArray APIとobjectEnumeratorオプションを確認してください。

5
Eric
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];
1
falconcreek

これが私が使う便利な関数です:

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