开发者

How to merge paths (NSString) in xcode?

Imagine you have two paths.

http://myserver.com/path1/path2 + /path1/开发者_C百科path2/cache/image1.jpg = http://myserver.com/path1/path2/cache/image1.jpg

Both path strings could have more or less path components.

So what I'm asking is how to find the equal part in the strings and then remove that part from one of the strings?


You have no idea whether the "equal" parts are really equal or not. It's not uncommon to have, eg, paths like .../part1/part1/part1/...

For the mechanics of dealing with the paths, though, NSString has some nice methods -- lastPathComponent, stringByAppendindPathComponent, pathComponents, pathWithComponents, etc.


What about this:

- (NSString *)mergeStringsPrefix:(NSString *)prefix suffix:(NSString *)suffix
{
    NSString *string = [NSString stringWithFormat:@"%@", prefix];

    NSArray *prefixComponents = [prefix pathComponents];
    NSArray *suffixComponents = [suffix pathComponents];

    if ([prefixComponents count] == 0) return [string retain]; 
    int rootIndex = [suffixComponents indexOfObject:@"/"];
    int index = 1;
    if (rootIndex == NSNotFound || rootIndex != 0) index = 0;

    int startIndex = [prefixComponents indexOfObject:[suffixComponents objectAtIndex:index]];
    if (startIndex == NSNotFound) return nil;

    if ([suffixComponents count] - index < [prefixComponents count] - startIndex) return nil;

    // fing length and check merge compatability
    BOOL equalParts = YES;
    for (int i=startIndex; i<[prefixComponents count] && equalParts; i++, index++)
    {
        NSString *el1 = [prefixComponents objectAtIndex:i];
        NSString *el2 = [suffixComponents objectAtIndex:index];

        if ([el1 compare:el2] != NSOrderedSame) equalParts = NO;
    }
    if (!equalParts) return nil;
    // merge
    for (int i=index; i<[suffixComponents count]; i++)
    {
        string = [string stringByAppendingFormat:@"/%@", [suffixComponents objectAtIndex:i]];
    }

    return [string retain];
}


This should do for you:

NSString* path1 = @"http://myserver.com/path1/path2";
NSString* path2 = @"/path1/path2/cache/image1.jpg";

NSMutableArray* path1Components = [NSMutableArray arrayWithArray:[path1 componentsSeparatedByString:@"/"]];
NSMutableArray* path2Components = [NSMutableArray arrayWithArray:[path2 componentsSeparatedByString:@"/"]];
[path2Components removeObjectAtIndex:0];

if ([path1Components containsObject:[path2Components objectAtIndex:0]]) {

    NSUInteger objectIndex = [path1Components indexOfObject:[path2Components objectAtIndex:0]];

    [path1Components removeObjectsInRange:NSMakeRange(objectIndex, [path1Components count]-objectIndex)];

    [path1Components addObjectsFromArray:path2Components];

    NSString* mergedPath = [path1Components componentsJoinedByString:@"/"];

    NSLog(@"%@",mergedPath);

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜