想象一下,你有两条路。
http://myserver.com/path1/path2 + /path1/path2/cache/image1.jpg = http://myserver.com/path1/path2/cache/image1.jpg
两个路径字符串都可以有更多或更少的路径组件。
所以我要问的是如何在字符串中找到相等的部分,然后从其中一个字符串中删除该部分?
答案 0 :(得分:1)
您不知道“相等”部分是否真的相同。例如,路径如... / part1 / part1 / part1 /...
并不罕见对于处理路径的机制,NSString有一些不错的方法 - lastPathComponent,stringByAppendindPathComponent,pathComponents,pathWithComponents等。
答案 1 :(得分:0)
这个怎么样:
- (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];
}
答案 2 :(得分:-2)
这应该适合你:
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);
}