Extract 2 strings from an NSString separated by a special character

爷,独闯天下 提交于 2019-12-20 19:08:08

问题


i have an NSString like "Hello - this is me". I want to search for the "-" and put the text before and after the "-" in two separate strings.

Anyone knows how to do that the best way?

greets Max


回答1:


NSArray *subStrings = [myString componentsSeparatedByString:@"-"]; //or rather @" - "
NSString *firstString = [subStrings objectAtIndex:0];
NSString *lastString = [subStrings objectAtIndex:1];
//Add some array range checking to it and you're done.



回答2:


NSString *myString = @"123-456-789-1234-2345-3456-4567";
NSArray *subStrings = [myString componentsSeparatedByString:@"-"];
for (int i = 0; i < [subStrings count]; i++) {
    NSLog(@"string on array position %d is : %@", i, [subStrings objectAtIndex:i]);
}


来源:https://stackoverflow.com/questions/5614681/extract-2-strings-from-an-nsstring-separated-by-a-special-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!