Split NSString and Limit the response

吃可爱长大的小学妹 提交于 2019-12-23 21:29:56

问题


I have a string Hello-World-Test, I want to split this string by the first dash only.

String 1:Hello String 2:World-Test

What is the best way to do this? What I am doing right now is use componentsSeparatedByString, get the first object in the array and set it as String 1 then perform substring using the length of String 1 as the start index.

Thanks!


回答1:


I added a category on NSString to split on the first occurrence of a given string. It may not be ideal to return the results in an array, but otherwise it seems fine. It just uses the NSString method rangeOfString:, which takes an NSString(B) and returns an NSRange showing where that string(B) is located.

@interface NSString (Split)

- (NSArray *)stringsBySplittingOnString:(NSString *)splitString;

@end

@implementation NSString (Split)

- (NSArray *)stringsBySplittingOnString:(NSString *)splitString
{
    NSRange range = [self rangeOfString:splitString];
    if (range.location == NSNotFound) {
        return nil;
    } else {
        NSLog(@"%li",range.location);
        NSLog(@"%li",range.length);
        NSString *string1 = [self substringToIndex:range.location];
        NSString *string2 = [self substringFromIndex:range.location+range.length];
        NSLog(@"String1 = %@",string1);
        NSLog(@"String2 = %@",string2);
        return @[string1, string2];
    }
}

@end



回答2:


Use rangeOfString to find if split string exits and then use substringWithRange to create new string on bases of NSRange.

For Example :

 NSString *strMain = @"Hello-World-Test";
 NSRange match = [strMain rangeOfString:@"-"];
if(match.location != NSNotFound)
{

    NSString *str1 = [strMain substringWithRange: NSMakeRange (0, match.location)];
    NSLog(@"%@",str1);
    NSString *str2 = [strMain substringWithRange: NSMakeRange (match.location+match.length,(strMain.length-match.location)-match.length)];
    NSLog(@"%@",str2);
}


来源:https://stackoverflow.com/questions/14252029/split-nsstring-and-limit-the-response

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