Split one string into different strings

后端 未结 5 578
不知归路
不知归路 2020-12-15 21:06

i have the text in a string as shown below

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

Basically i woul

相关标签:
5条回答
  • 2020-12-15 21:52
    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 讨论(0)
  • 2020-12-15 21:58

    Look at NSString componentsSeparatedByString or one of the similar APIs.

    If this is a known fixed set of results, you can then take the resulting array and use it something like:

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

    If it is variable, look at the NSArray APIs and the objectEnumerator option.

    0 讨论(0)
  • 2020-12-15 21:59

    Here's a handy function I use:

    ///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 讨论(0)
  • 2020-12-15 22:04

    does objective-c have strtok()?

    The strtok function splits a string into substrings based on a set of delimiters. Each subsequent call gives the next substring.

    substr = strtok(original, ",|");
    while (substr!=NULL)
    {
       output[i++]=substr;
       substr=strtok(NULL, ",|")
    }
    
    0 讨论(0)
  • 2020-12-15 22:10

    I would use -[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 讨论(0)
提交回复
热议问题