objective c - Remove dot/double dot from path in iOS -
all single dot components of path must removed.
for example, "abi/./bune" should normalized "abi/bune".
all double dot components of path must removed, along parent directory. example, "abi/ba/../bune" should normalized "abi/bune".
without using regular expressions. idea how achieve?
@daniel's answer correct one. since there discussion in comments question, decided provide code example @ rey gonzales's idea of tokenizing string , using stack.
warning: code here purely educational purposes (because asked in comments question). in real life stick @daniel's solution.
the code might this:
-(nsstring *)normalizepath:(nsstring *)path { nsarray *pathcomponents = [path componentsseparatedbystring:@"/"]; nsmutablearray *stack = [[nsmutablearray alloc] initwithcapacity:pathcomponents.count]; (nsstring *pathcomponent in pathcomponents) { if ([pathcomponent isequaltostring:@".."]) { [stack removelastobject]; } else { if (![pathcomponent isequaltostring:@"."]) { [stack addobject:pathcomponent]; } } } return [stack componentsjoinedbystring:@"/"]; }
Comments
Post a Comment