casillas
casillas

Reputation: 16793

Remove dot/double dot from path in iOS

All single dot components of the path must be removed.

For example, "abi/./bune" should be normalized to "abi/bune".

All double dot components of the path must be removed, along with their parent directory. For example, "abi/ba/../bune" should be normalized to "abi/bune".

without using regular expressions. Any idea how to achieve?

Upvotes: 0

Views: 795

Answers (2)

FreeNickname
FreeNickname

Reputation: 7764

@Daniel's answer is the correct one. But since there was a discussion in the comments to the question, I decided to provide a code example for @ Rey Gonzales's idea of tokenizing a string and using a stack.

WARNING: this code is here for purely educational purposes (because someone asked for it in the comments to the question). In real life stick to the @Daniel's solution.

The code might look like this:

-(NSString *)normalizePath:(NSString *)path {
    NSArray *pathComponents = [path componentsSeparatedByString:@"/"];

    NSMutableArray *stack = [[NSMutableArray alloc] initWithCapacity:pathComponents.count];

    for (NSString *pathComponent in pathComponents) {
        if ([pathComponent isEqualToString:@".."]) {
            [stack removeLastObject];
        }
        else {
            if (![pathComponent isEqualToString:@"."]) {
                [stack addObject:pathComponent];
            }
        }
    }

    return [stack componentsJoinedByString:@"/"];
}

Upvotes: 1

Daniel Larsson
Daniel Larsson

Reputation: 6394

This can be achieved by calling

NSString *standardizedPath = [path stringByStandardizingPath];

For example:

"/usr/bin/./grep"         ->    "/usr/bin/grep"
"/usr/include/objc/.."    ->    "/usr/include"

Worth noticing is that this also removes any initial components of /private and tries to expand any initial tilde expressions using stringByExpandingTildeInPath.

Upvotes: 5

Related Questions