Remove part of a string before the first forward slash

I have a string

NSString *str = @"xyz/en/ABOUT/hello";

I need to remove all characters before the first slash.

My output should be like this :


but I cannot simply replace @"xyz", because the contents before the first slash are dynamic.

4 answers

  • answered 2017-10-11 10:15 armnotstrong

    first split the string:

    NSArray *array1 = [str componentsSeparatedByString:@"/"]

    then join the string:

    NSString *joinedString = [[array1 subarrayWithRange:NSMakeRange(1, [array1 count] - 1)] componentsJoinedByString:@"/"];

    to add the first '/' back

    joinedString = [@"/" stringByAppendingString:joinedString]

    There should be a regex way of doing this, but rarely using that unless have to.

  • answered 2017-10-11 11:28 Brian Hamm

    Swift 4

    let str = "xyz/en/ABOUT/hello"
    let arr = str.components(separatedBy: "/")
    // ["xyz","en","ABOUT","hello"]
    let str2 = "/\(arr.dropFirst().joined(separator: "/"))" 
    // "/en/ABOUT/hello"

  • answered 2017-10-11 14:07 Rahul Kumar


    NSString *str = @"xyz/en/ABOUT/hello";
    NSUInteger index = [str rangeOfString:@"/"].location;
    NSString *myString = [str substringFromIndex:index];
    NSLog(@"final string: %@", myString);    // final string:  /en/ABOUT/hello


    let str = "xyz/en/ABOUT/hello"
    let index = str.range(of: "/")?.lowerBound
    let myString: String? = str.substring(from: index!)
    print("final string: ", myString!)   // final string:  /en/ABOUT/hello

  • answered 2017-10-11 21:44 Josh Caswell

    Looks like you're working with a file path. So, use path manipulation methods:

    @implementation NSString (MorePaths)
    - (NSString *)WSSDroppingFirstRelativePathComponent
        if ([self isAbsolutePath]) {
            return self;
        NSArray * trailingComponents = [[self pathComponents] WSSDroppingFirst];
        return [NSString pathWithComponents:trailingComponents];
    @implementation NSArray (Dropping)
    - (NSArray *)WSSDroppingFirst
        NSRange trailingRange = NSMakeRange(1, [self count] - 1);
        return [self subarrayWithRange:trailingRange];

    If this is actually a URL, make the category on NSURL instead of NSString (and then you can't use isAbsolutePath).