Malene
Malene

Reputation: 55

How to cut out parts of NSString?

@"/News/some news text/" 
@"/News/some other news text/" 
@"/About/Some about text/" 
@"/Abcdefg/Some abcdefg text/some more abcdefg text"

How do I cut out the first part of the strings, so that I end up with the following strings?

@"/News/"
@"/News/"
@"/About/"
@"/Abcdefg/"

Upvotes: 0

Views: 4983

Answers (2)

Peter Hosey
Peter Hosey

Reputation: 96393

If these are pathnames, you may want to look into the path-related methods of NSString, such as pathComponents and pathByDeletingLastPathComponent.

While it's pretty unlikely that the path separator is ever going to change, it's nonetheless a good habit to not rely on such things and use dedicated path-manipulation methods in preference to assuming that the path separator will be a certain character.

EDIT from the year 2013: Or use URLs (more specifically, NS/CFURL objects), which Apple has made pretty clear are the proper way to refer to files from now on, and are necessary for some tasks in a sandbox.

Upvotes: 2

grahamparks
grahamparks

Reputation: 16296

Use componentsSeparatedByString: to break the string up:

NSArray *components=[string componentsSeparatedByString:@"/"];
if ([components count]>=2) {
     // Text after the first slash is second item in the array
    return [NSString stringWithFormat:@"/%@/",[components objectAtIndex:1]];
} else {
    return nil; // Up to you what happens in this situation
}

Upvotes: 8

Related Questions