I have a NSString which is a URL. This URL need to be cut:
NSString *myURL = #"http://www.test.com/folder/testfolder";
NSString *test = [myURL stringByReplacingCharactersInRange:[myURL rangeOfString:#"/" options:NSBackwardsSearch] withString:#""];
I have this URL http://www.test.com/folder/testfolder and I want that the test variable should have the value http://www.test.com/folder/, so the testfolder should be cut.
So I tried to find the NSRange testfolder to replace it with an empty string.
But it does not work. What I am doing wrong?
You can turn it into a URL and use -[NSURL URLByDeletingLastPathComponent]:
NSString *myURLString = #"http://www.test.com/folder/testfolder";
NSURL *myURL = [NSURL URLWithString:myURLString];
myURL = [myURL URLByDeletingLastPathComponent];
myURLString = [myURL absoluteString];
Try this:
NSString *myURL = #"http://www.test.com/folder/testfolder";
NSString *test = [myURL stringByDeletingLastPathComponent];
NSLog(#"%#", test);
you should get > http://www.test.com/folder/
You can't use the NSRange returned by [myURL rangeOfString:#"/" options:NSBackwardsSearch] because its length is "1". So to keep with your idea to use NSRange (other replies using stringByDeletingLastPathComponent seems to be very valid too), here is how you could do it :
NSRange *range=[myURL rangeOfString:#"/" options:NSBackwardsSearch];
NSString *test = [myURL stringByReplacingCharactersInRange:NSMakeRange(range.location,test.length-range.location) withString:#""];
Related
I have a string like so:
NSString *path = #"\\fake\aaa\bbb\ccc\ddd\eee.pdf";
and I split the string into an array like so:
NSArray *array = [path componentsSeparatedByString:#"\"];
Now there are two things I need here.
I need a string with everything except eee.pdf
I need the last item in the array as a string (eee.pdf)
How would I do this?
Just for fun, there is a little-known way to get an NSURL with its benefit from a windows file path
NSString *path = #"\\\\fake\\aaa\\bbb\\ccc\\ddd\\eee.pdf";
NSURL *url = CFBridgingRelease(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)path, kCFURLWindowsPathStyle, false));
NSString *fileName = url.lastPathComponent;
NSString *parentDirectory = url.URLByDeletingLastPathComponent.path;
Finally you have to convert parentDirectory back to windows path style (backslashes).
But if you mean POSIX paths used in OS X, it's much easier
NSString *path = #"/fake/aaa/bbb/ccc/ddd/eee.pdf";
NSURL *url = [NSURL fileURLWithPath:path];
NSString *fileName = url.lastPathComponent;
NSString *parentDirectory = url.URLByDeletingLastPathComponent.path;
I think you're trying to get the filepath and filename from a full path. There are better ways of doing that. But since you simply asked for the question, here's my answer. Please note that this is not the best approach. In addition, you have to escape the backslashes by using a preceding backslash.
NSString *path = #"\\fake\\aaa\\bbb\\ccc\\ddd\\eee.pdf";
NSArray *array = [path componentsSeparatedByString:#"\\"];
NSMutableArray *removedArray = [[NSMutableArray alloc] init];
for(int i=0; i< array.count -1; i++){
[removedArray addObject:[array objectAtIndex:i]];
}
NSString *joinedString =[removedArray componentsJoinedByString:#"\\"];
NSString *fileName = [array lastObject];
NSLog(#"Path: %#", joinedString);
NSLog(#"Filename: %#", fileName);
For the last element use the lastObject property of the NSArray.
For a string without the last element use subarrayWithRange: using array.count-1 for the NSRange length.
Then join the remaining array with componentsJoinedByString:.
NSString *fileName = [array lastObject];
NSArray *newArray = [array subarrayWithRange:NSMakeRange(0, array.count-1)];
NSString *directoryPath = [newArray componentsJoinedByString:#"\\"];
This question already has answers here:
How to take NSString after specific character which occurs multiple time in NSString?
(3 answers)
Closed 8 years ago.
I have an NSString which represents paths like
.../App/Some/Directory/myClass.mm
Now I want to trim
.../App/Some/Directory/
to get only the Class' name/file. How to achieve this?
You can convert your string to a NSURL, and the get the lastPathComponent to get the "myClass.mm" you want.
NSString* filePath = #"/App/Some/Directory/myClass.mm";
NSURL *url = [NSURL URLWithString:filePath];
NSString* lastComponent = [url lastPathComponent];
Should do the trick.
You can separate the string into components (using the / as the separator), and then the filename will be the last element of the output array.
NSString *input = #".../App/Some/Directory/myClass.mm";
NSArray *array = [input componentsSeparatedByString:#"/"];
NSLog( #"%#", [array lastObject] );
NSString class has lastPathComponent method, also you can solve your problem like this:
NSString *path;
NSString *trimmed;
NSRange range = [path rangeOfString:#"/" options:NSBackwardsSearch];
if (range.location != NSNotFound)
trimmed = [path substringFromIndex:range.location+1];
else
trimmed = path;
NSString* str = #"/App/Some/Directory/myClass.mm";
NSRange replaceRange = [str rangeOfString:#"/myClass.mm"];
if (replaceRange.location != NSNotFound){
NSString* result = [str stringByReplacingCharactersInRange:replaceRange withString:#""];
NSLog(#"Result :%#",result);
}
Is there a way to concatenate two strings and inject a character. I have :
NSString *firstString = #"http://www.stackoverflow.com";
NSString *secondString = #"supercooloptions";
NSString *result = [firstString stringByAppendingString: secondString];
NSLog(#"the final string with "/" injection = %#", result);
I'd like the final string with "/" injected = www.stackoverflow.com/supercooloptions
You can use a different method - for example, stringWithFormat:
NSString *result = [NSString stringWithFormat:#"%#/%#", firstString, secondString];
For this specific case, use stringByAppendingPathComponent:
NSString *result = [firstString stringByAppendingPathComponent:secondString];
I'm appending a string to a url which then inputs into a database, it works with a single worded string e.g
NSString * string = #"one";
however if my string has two words such as
NSString * string = #"one two";
it does not work. Please see the code below.
NSMutableString * urlString = [NSMutableString stringWithString:url];
[urlString appendString:[NSString stringWithFormat:#"?%#=%#",kWord,word]];
The problem obviously lies with stringWithFormat;
turns out the problem is with the space.
Space characters (and certain others) are not allowed in URLs. You need to convert the space to %20. Here is the proper solution:
NSString *url = #"http://example.com/process.php";
NSString *kword = #"param";
NSString *word = #"one two";
NSMutableString * urlString = [url mutableCopy];
[urlString appendFormat:#"?%#=%#", kWord, [word stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
I have tried couple exampes here, hope it helps.
NSString *string1 = #"String1";
NSString *string2 = #"String2 String3";
NSMutableString *appendingString=[NSMutableString stringWithString: [string1 stringByAppendingString:string2]];
NSLog(#"String1:%# String2:%#",string1,string2);
NSLog(#"StringwithAppend:%#",appendingString);
//------
NSString *url=#"www.abc.com";
NSMutableString * urlString = [NSMutableString stringWithString:url];
NSLog(#"URL String before append:%#",urlString);
NSString *kWord=#"key";
NSString *word=#"word";
[urlString appendString:[NSString stringWithFormat:#"?%#=%#",kWord,word]];
NSLog(#"URL String after append:%#",urlString);
Console Log:
String1:String1 String2:String2 String3
StringwithAppend:String1String2 String3
URL String before append:www.abc.com
URL String after append:www.abc.com?key=word
Try it this way.
NSString * urlString= [NSString stringWithFormat:#"%#?%#=%#", url, kword, word];
Times like this and my Objective-C noobness shows. :-/
So, the more I work on a routine to do this, the more complex it's becoming, and I'm wondering if there isn't just a simple method to change the name of a filename in a path. Basically, I want to change #"/some/path/abc.txt to #"/some/path/xyz.txt -- replacing the filename portion but not changing the path or extension.
Thanks!
Try the following:
NSString* initPath = ...
NSString *newPath = [[NSString stringWithFormat:#"%#/%#",
[initPath stringByDeletingLastPathComponent], newFileName]
stringByAppendingPathExtension:[initPath pathExtension]];
What Vladimir said, just broken down more to make it a little easier to read:
NSString *pathToFile = #"/Path/To/File.txt";
NSString *oldFileName = [pathToFile lastPathComponent];
NSString *newFileName = [#"Document" stringByAppendingPathExtension:[oldFileName pathExtension];
NSString *newPathToFile = [pathToFile stringByDeletingLastPathComponent];
[newPathToFile stringByAppendingString:newFileName];
Take a look at the "Working With Paths" section of the NSString docs. In particular, lastPathComponent, pathExtension and stringByDeletingPathExtension: should do what you want.
You can try something like this:
NSRange slashRange = [myString rangeOfString:#"\\" options:NSBackwardsSearch];
NSRange periodRange = [myString rangeOfString:#"." options:NSBackwardsSearch];
NSString *newString = [myString stringByReplacingCharactersInRange:NSMakeRange(slashRange.location, periodRange.location) withString:#"replacement-string-here"];
What this code does is it gets the location of the \ and . characters and performs a backwards search so that it returns the last occurrence of it in the string.
Then, it creates a new range based on those previous ranges and replaces the contents in that range with stringByReplacingCharactersInRange:.
Try this:
NSString* path = [startString stringByDeletingLastPathComponent];
NSString* extension = [startString pathExtension];
NSString* replacementFileName = [#"foo" stringByAppendingPathExtension: extension];
NSString result = [path stringByAppendingPathComponent: replacementFileName];