function to get the file name of an URL

Posted by user262325 on Stack Overflow See other posts from Stack Overflow or by user262325
Published on 2010-03-14T00:04:23Z Indexed on 2010/03/14 0:15 UTC
Read the original article Hit count: 561

Filed under:

Hello everyone

I have some source code to get the file name of an url

for example:

http://www.google.com/a.pdf

I hope to get a.pdf

because the way to join 2 NSStrings I can get is 'appendString' which only for adding a string at right side, so I planned to check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop the checking, return string fdp.a , after that I change fdp.a to a.pdf

source codes are below

-(NSMutableString *) getSubStringAfterH :  originalString:(NSString *)s0 
{
    NSInteger i,l;

    l=[s0 length];

    NSMutableString *h=[[NSMutableString alloc] init];

    NSMutableString *ttt=[[NSMutableString alloc] init  ];
     for(i=l-1;i>=0;i--) //check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop
    {

        ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
         if([ttt isEqualToString:@"/"]) 
        { 

            break;

        }


        else
        {


             [h appendString:ttt];

        } 



    }
     [ttt release];

    //below are to change the sequence of char in h
    // txt.edcba ->  abcde.txt

    NSMutableString *h1=[[[NSMutableString alloc] initWithFormat:@""] autorelease];

    for (i=[h length]-1;i>=0;i--)
    {
        NSMutableString *t1=[[NSMutableString alloc] init ];
        t1=[h substringWithRange:NSMakeRange(i, 1)];



        [h1 appendString:t1];


        [t1 release];

    } 
    [h release];

    return h1;

}

h1 can reuturn the coorect string a.pdf, but if it returns to the codes where it was called, after a while system reports 'double free * set a breakpoint in malloc_error_break to debug'

I checked a long time and foudn that if I removed the code

ttt=[s0 substringWithRange:NSMakeRange(i, 1)];

everything will be Ok (of course getSubStringAfterH can not returns the corrent result I expected.), no error reported.

I try to fix the bug a few hours, but still no clue.

Welcome any comment

Thanks interdev

© Stack Overflow or respective owner

Related posts about iphone