3

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!

MiuMiu
  • 1,905
  • 2
  • 19
  • 28

2 Answers2

5

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
MaxGabriel
  • 7,617
  • 4
  • 35
  • 82
3

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);
}
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
  • 1
    Why call rangeOfString twice? Call it once and save the location. And it would be easier to use substringFromIndex and substringToIndex to get the two substrings. – rmaddy Jan 10 '13 at 07:02