Trim NSString to specific pathComponent [duplicate] - objective-c

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);
}

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

Inject a character while concatenating with stringByAppendingString

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

appending string- works with string with one word but not two

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

How to parse a string format like [***]***?

I need to parse a string like [abc]000, and what I want to get is an array containing abc and 000. Is there an easy way to do it?
I'm using code like this:
NSString *sampleString = #"[abc]000";
NSArray *sampleParts = [sampleString componentsSeparatedByString:#"]"];
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:#"["] lastObject];
NSString *lastPart = [sampleParts lastObject];
But it's inefficient and didn't check whether the string is in a format like [**]**.
For this simple pattern, can just parse yourself like:
NSString *s = #"[abc]000";
NSString *firstPart = nil;
NSString *lastPart = nil;
if ([s characterAtIndex: 0] == '[') {
NSUInteger i = [s rangeOfString:#"]"].location;
if (i != NSNotFound) {
firstPart = [s substringWithRange:NSMakeRange(1, i - 1)];
lastPart = [s substringFromIndex:i + 1];
}
}
Or you could learn to use the NSScanner class.
As always, there are lots of ways to do this.
OPTION 1
If these are fixed length strings (each part is always three characters) then you can simply get the substrings directly:
NSString *sampleString = #"[abc]000";
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)];
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
OPTION 1 (shortened)
NSArray *parts = #[ [sampleString substringWithRange:NSMakeRange(1, 3)],
[sampleString substringWithRange:NSMakeRange(5, 3)] ];
NSLog(#"%#", parts);
OPTION 2
If they aren't always three characters, then you can use NSScanner:
NSString *sampleString = #"[abc]000";
NSScanner *scanner = [NSScanner scannerWithString:sampleString];
// Skip the first character if we know that it will always start with the '['.
// If we can not make this assumption, then we would scan for the bracket instead.
scanner.scanLocation = 1;
NSString *left, *right;
// Save the characters until the right bracket into a string which we store in left.
[scanner scanUpToString:#"]" intoString:&left];
// Skip the right bracket
scanner.scanLocation++;
// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist...
[scanner scanUpToString:#"\0" intoString:&right];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
RESULTS (for all options)
2013-05-10 00:25:02.031 Testing App[41906:11f03] (
abc,
000
)
NOTE
All of these assume well-formed strings, so you should include your own error checking.
try like this ,
NSString *sampleString = #"[abc]000";
NSString *pNRegex = #"\\[[a-z]{3}\\][0-9]{3}";
NSPredicate *PNTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pNRegex];
BOOL check=[PNTest evaluateWithObject:sampleString ];
NSLog(#"success:%i",check);
if success comes as 1 then you can perform the action for separating string into array.

Objective-C: Substring and replace

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