What is the best way to cut path from NSString? - objective-c

I am new in Cocoa. I have NSString . that looks like this
Attribute: OtherAttributte: /users/user/etc...
What is the best way to cut off and store separately that Path?
Thanks.

You can use rangeOfString and substringFromIndex.
NSString *path = #"Attribute: OtherAttributte: /users/user/etc";
NSRange x = [path rangeOfString:#"/"];
NSString *final = [path substringFromIndex:x.location];
This will work if your path starts with #"/".

Use rangeOfString:#"/" to find the location of the first forward slash, and then substringFromIndex: to extract it.

First approach:
NSString *path = #"tmp/scratch";
NSArray *pathComponents = [path pathComponents];
Second approach:
NSString *path = #" /users/user/etc";
NSArray *parts = [list componentsSeparatedByString:#"/"];

I would use componentsSeparatedByString: which is a method of NSString.

I'm not fully sure whether you're asking how to get the path from the string of arguments, or how to get a part of the path, so I'll outline how I'd do both in separate steps below:
NSString *args = #"attribute1: attribute2: /users/user/etc";
NSString *path = [[args componentsSeparatedByString:#":"] last];
NSArray *pathComponents = [path pathComponents];
Obviously this relies on the path being the value of the final argument, but you could use a different means finding the path in the array produced from args.
Details of NSString methods can be found here, and NSArray methods here.

Related

Objective-C Split a String and get last item

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:#"\\"];

Split NSString in exactly two pieces

Which is the optimum way to split an NSString in two pieces? My idea was to split a filename in two parts the filename itself and the extension. I would like to know which could be the most simple one.
NSStringoffers some of its own implementations that will do exactly what you want for filenames and paths.
See https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/doc/uid/20000154-SW38 and there for example lastPathComponentor pathExtension.
[yourFilePath lastPathComponent] gives you the filename of a given path. [yourFilePath pathExtension] gives you the extension. Note this works for NSURL as well, but expects a valid path or URL respectively.
NSString *filename = [sFilename lastPathComponent]; // this will give you pure filename if it's a path already
NSArray *filenameParts = [filename componentsSeparatedByString:#"."];
if ([filenameParts count] == 2) {
NSString *file = [filenameParts objectAtIndex:0];
NSString *fileExtension = [filenameParts objectAtIndex:1];
...
}

How to write a NSString array object in one go?

My problem is that I know NSString may used as an array and in my code I wrote it as such:
NSString *loadBackground[3];
loadBackground[0] = #"background1";
loadBackground[1] = #"background2";
loadBackground[2] = #"background3";
Is it possible to write the same code in one line instead of 4 lines?
Please use NSArray instead of c-arrays
NSArray *array = [NSArray arrayWithObjects:#"background1", #"background1" , #"background1", nil];
accessing a string:
NSString *aString = [array objectAtIndex:1]
Use an NSArray instead:
NSArray *bgs = [#"bg1,bg2,bg3" componentsSeparatedByString:#","]; // => [#"bg1", #"bg2", #"bg3"];
try this :
NSString *st11[3]={#"hai",#"hai1",#"hai2"};
NSLog(#"%#,%#,%#",st11[0],st11[1],st11[2]);
Not sure why you're not using NSArray, but if you really want to do it you can do:
NSString *loadBackground[3] = {#"background1", #"background2", #"background3"};
NSString *strs[3]={#"str1",#"str2",#"str3"};
use: strs[0];

How to remove a section of a string using escape character

I have a set of NSString representing the names of the files in a directory. These names are structured this way:
XXXXXXXXX_YYYY_AAAA.ext
All the sections separated by "_" are of variable length and I would only have the first.
How can I separate the first part from the other?
Find the position of the '_' character, then get a substring 0 through that position. Note that substringToIndex: does not include the character at the index position.
NSRange r = [myString rangeOfString:#"_"];
NSString *res = [myString substringToIndex:r.location];
Take a look at the NSString method componentsSeparatedByString:. That will tokenize a string and return you an array. Something like this:
NSArray *array = [#"XXXXXXXXX_YYYY_AAAA.ext" componentsSeparatedByString:#"_"];
NSString *firstToken = [array objectAtIndex:0];
NSArray *array = [yourString componentsSeparatedByString:#"_"];
NSString *Xs = [array objectAtIndex:0];
Try componentsSeparatedByString: under the heading Dividing Strings.
NSString Docs

NSString: changing a filename but not the extension

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];