2010-08-12 13 views
16

ho il testo in una stringa come illustrato di seguitoSplit una stringa in diverse stringhe

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

Fondamentalmente vorrei ciascuno dei numeri in diverse stringhe al messaggio esempio

NSString *Number1 = 011597464952 
NSString *Number2 = 01521545545 
etc 
etc 
NSString *Message = Hello this is were the message is. 

lo farei Mi piace dividerlo da una stringa che lo contiene tutto

risposta

45

userei -[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

ha l'obiettivo-c ha strtok()?

La funzione strtok divide una stringa in sottostringhe in base a un insieme di delimitatori. Ogni chiamata successiva fornisce la sottostringa successiva.

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

No, ma C fa, e da allora Objective-C è un superset rigorosa di C, Objective-C lo ottiene gratuitamente. – Allyn

+0

Puoi spiegare per favore :) – user393273

+0

non penso che questo funzionerà sull'obiettivo c – user393273

5

Guarda NSStringcomponentsSeparatedByString o di una delle API simili.

Se si tratta di un insieme fisso noto di risultati, è possibile poi prendere la matrice risultante e usarlo qualcosa come:

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

Se è variabile, guarda le NSArray API e l'opzione objectEnumerator.

+0

sì, l'ho scoperto prima, ma come faccio a mettere ogni array in una stringa separata? – user393273

+0

Aggiunto un po 'più di dettagli al post originale. – 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

Ecco una comoda funzione che uso:

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