Garbage at the end of `NSString` on xCode after calling the stringByReplacingCharactersInRange` method

I am using the following code to replace the file extension:

NSString *fileOriginal = [url lastPathComponent];
NSString *fileSource = @"";
NSRange range = [fileOriginal rangeOfString:@"." options:NSBackwardsSearch];
if (range.length > 0) {
    range.length = fileOriginal.length - range.location;
    fileSource = [fileOriginal stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@".%@", @"cpp"]];
} else {
    fileSource = [fileOriginal stringByAppendingString:[NSString stringWithFormat:@".%@", gFileExtension]];
}

      

The code works fine. But the debugger shows garbage at the end NSString

:

enter image description here

Same result if I tried adding retain

to lines. What happened?

+3


source to share


1 answer


Assuming your definition is gFileExtension

valid, why not try this:

NSString *fileSource;
if ([[fileOriginal pathExtension] length] > 0)
{
    fileSource = [[fileOriginal stringByDeletingPathExtension] stringByAppendingPathExtension:gFileExtension];
}
else
{
    fileSource = [fileOriginal stringByAppendingPathExtension:gFileExtension];
}

      



By using the path handling built in NSString

, you don't need to worry about the point; it's done for you.

+1


source







All Articles