Подтвердить что ты не робот

Разделить одну строку на разные строки

У меня есть текст в строке, как показано ниже

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.

Мне хотелось бы, чтобы это было разделено на одну строку, содержащую все

4b9b3361

Ответ 1

Я бы использовал -[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);
}

Ответ 2

Посмотрите NSString componentsSeparatedByString или один из похожих API.

Если это известный фиксированный набор результатов, вы можете взять полученный массив и использовать его что-то вроде:

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

Если переменная, просмотрите API NSArray и objectEnumerator.

Ответ 3

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

Ответ 4

имеет objective-c strtok()?

Функция strtok разбивает строку на подстроки на основе набора разделителей. Каждый последующий вызов дает следующую подстроку.

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

Ответ 5

Здесь удобная функция, которую я использую:

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