Skip to content

Instantly share code, notes, and snippets.

@Shilo
Created August 31, 2013 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shilo/6397570 to your computer and use it in GitHub Desktop.
Save Shilo/6397570 to your computer and use it in GitHub Desktop.
NSString category for string splitting with a limit.
//
// NSString+ComponentsLimit.h
//
// Created by Shilo White on 8/31/13.
// Copyright (c) 2013 Shilocity Productions. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (ComponentsLimit)
- (NSArray *)componentsSeparatedByString:(NSString *)separator limit:(NSUInteger)limit;
@end
//
// NSString+ComponentsLimit.m
//
// Created by Shilo White on 8/31/13.
// Copyright (c) 2013 Shilocity Productions. All rights reserved.
//
#import "NSString+ComponentsLimit.h"
@implementation NSString (ComponentsLimit)
- (NSArray *)componentsSeparatedByString:(NSString *)separator limit:(NSUInteger)limit
{
if (limit == 0)
return [self componentsSeparatedByString:separator];
NSArray *allComponents = [self componentsSeparatedByString:separator];
NSMutableArray *components = [NSMutableArray arrayWithCapacity:MIN(limit, allComponents.count)];
int i = 0;
for (NSString *component in allComponents)
{
if (i >= limit)
{
[components addObject:[[allComponents subarrayWithRange:NSMakeRange(i, allComponents.count-1)] componentsJoinedByString:separator]];
break;
}
[components addObject:component];
i++;
}
return components;
}
@end
@stephanedupont
Copy link

stephanedupont commented Feb 6, 2021

This doesn't work at all and crashes because:

  • it's not allComponents.count-1 but allComponents.count-i
  • it's not i >= limit but limit - 1

Implementation that works:

if (limit == 0)
    return [self componentsSeparatedByString:separator];

NSArray *allComponents = [self componentsSeparatedByString:separator];
if (allComponents.count <= limit) return allComponents;

NSMutableArray *components = [NSMutableArray arrayWithCapacity:MIN(limit, allComponents.count)];

int i = 0;
for (NSString *component in allComponents) {
    if (i == (limit - 1)) {
        [components addObject:
                [[allComponents subarrayWithRange:NSMakeRange(i, allComponents.count - i)]
                        componentsJoinedByString:separator]];
        break;
    }
    [components addObject:component];
    i++;
}

return components;

@Shilo
Copy link
Author

Shilo commented May 6, 2021

Thank you! Unfortunately this code is very old and I no longer use Objective-C as well as have no time. So I can not validate any of it. I will take your word for it, thank you for the effort and contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment