1

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 :

"/en/ABOUT/hello"

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

jscs
  • 63,694
  • 13
  • 151
  • 195
user6788419
  • 7,196
  • 1
  • 16
  • 28

3 Answers3

3

Objective-C

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

Swift3

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
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22
0

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.

armnotstrong
  • 8,605
  • 16
  • 65
  • 130
0

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

@implementation NSString (MorePaths)

- (NSString *)WSSDroppingFirstRelativePathComponent
{
    NSArray * trailingComponents = [[self pathComponents] WSSDroppingFirst];
    return [NSString pathWithComponents:trailingComponents];
}

@end

@implementation NSArray (Dropping)

- (NSArray *)WSSDroppingFirst
{
    NSRange trailingRange = NSMakeRange(1, [self count] - 1);
    return [self subarrayWithRange:trailingRange];
}

@end

If this is actually a URL, make the category on NSURL instead of NSString.

jscs
  • 63,694
  • 13
  • 151
  • 195