Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split NSString and Limit the response

Tags:

ios

nsstring

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!

like image 927
MiuMiu Avatar asked May 31 '26 07:05

MiuMiu


1 Answers

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
like image 150
MaxGabriel Avatar answered Jun 01 '26 21:06

MaxGabriel