Getting the last 2 directories of a file path - iphone

I have a file path of, for example /Users/Documents/New York/SoHo/abc.doc. Now I need to just retrieve /SoHo/abc.doc from this path.
I have gone through the following:
stringByDeletingPathExtension -> used to delete the extension from the path.
stringByDeletingLastPathComponent -> to delete the last part in the part.
However I didn't find any method to delete the first part and keep the last two parts of a path.

NSString has loads of path handling methods which it would be a shame not to use...
NSString* filePath = // something
NSArray* pathComponents = [filePath pathComponents];
if ([pathComponents count] > 2) {
NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];
NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];
}

I've written function special for you:
- (NSString *)directoryAndFilePath:(NSString *)fullPath
{
NSString *path = #"";
NSLog(#"%#", fullPath);
NSRange range = [fullPath rangeOfString:#"/" options:NSBackwardsSearch];
if (range.location == NSNotFound) return fullPath;
range = NSMakeRange(0, range.location);
NSRange secondRange = [fullPath rangeOfString:#"/" options:NSBackwardsSearch range:range];
if (secondRange.location == NSNotFound) return fullPath;
secondRange = NSMakeRange(secondRange.location, [fullPath length] - secondRange.location);
path = [fullPath substringWithRange:secondRange];
return path;
}
Just call:
[self directoryAndFilePath:#"/Users/Documents/New York/SoHo/abc.doc"];

Divide the string into components by sending it a pathComponents message.
Remove all but the last two objects from the resulting array.
Join the two path components together into a single string with +pathWithComponents:

Why not search for the '/' characters and determine the paths that way?

NSString* theLastTwoComponentOfPath;
NSString* filePath = //GET Path;
NSArray* pathComponents = [filePath pathComponents];
int last= [pathComponents count] -1;
for(int i=0 ; i< [pathComponents count];i++){
if(i == (last -1)){
theLastTwoComponentOfPath = [pathComponents objectAtIndex:i];
}
if(i == last){
theTemplateName = [NSString stringWithFormat:#"\\%#\\%#", theLastTwoComponentOfPath,[pathComponents objectAtIndex:i] ];
}
}
NSlog (#"The last Two Components=%#", theLastTwoComponentOfPath);

Related

How to remove starting 0's in uitextfield text in iphone sdk

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

IOS : NSString retrieving a substring from a string

Hey I am looking for a way to extract a string from another string. It could be any length and be in any part of the string so the usual methods don't work.
For example
http://bla.com/bla?id=%1234%&something=%888%
What I want to extract is from id=% to the next %.
Any idea's?
Use the rangeOfString method:
NSRange range = [string rangeOfString:#"id=%"];
if (range.location != NSNotFound)
{
//range.location is start of substring
//range.length is length of substring
}
You can then chop up the string using the substringWithRange:, substringFromIndex: and substringToIndex: methods to get the bits you want. Here's a solution to your specific problem:
NSString *param = nil;
NSRange start = [string rangeOfString:#"id=%"];
if (start.location != NSNotFound)
{
param = [string substringFromIndex:start.location + start.length];
NSRange end = [param rangeOfString:#"%"];
if (end.location != NSNotFound)
{
param = [param substringToIndex:end.location];
}
}
//param now contains your value (or nil if not found)
Alternatively, here's a general solution for extracting query parameters from a URL, which may be more useful if you need to do this several times:
- (NSDictionary *)URLQueryParameters:(NSURL *)URL
{
NSString *queryString = [URL query];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *parameters = [queryString componentsSeparatedByString:#"&"];
for (NSString *parameter in parameters)
{
NSArray *parts = [parameter componentsSeparatedByString:#"="];
if ([parts count] > 1)
{
NSString *key = [parts[0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [parts[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
result[key] = value;
}
}
return result;
}
This doesn't strip the % characters from the values, but you can do that either with
NSString *value = [[value substringToIndex:[value length] - 1] substringFromIndex:1];
Or with something like
NSString *value = [value stringByReplacingOccurencesOfString:#"%" withString:#""];
UPDATE: As of iOS 8+ theres a built-in class called NSURLComponents that can automatically parse query parameters for you (NSURLComponents is available on iOS 7+, but the query parameter parsing feature isn't).
Try this
NSArray* foo = [#"10/04/2011" componentsSeparatedByString: #"/"];
NSString* day = [foo objectAtIndex: 0];

iphone remove next string - leave rest of string after particular occurrence of string

In objective c how to Remove text after a string occurrence.
for example i have to remove a text after occurrence of text 'good'
'iphone is good but..' here i have to remove the but text in the end so the text will be now 'iphone is good'
Try with below code
NSString *str_good = #"iphone is good but...";
NSRange range = [str_good rangeOfString:#"good"];
str_good = [str_good substringToIndex:range.location+range.length];
NSString * a = #"iphone is good but..";
NSRange match = [a rangeOfString:#"good"];
NSString * b = [a substringToIndex:match.location+match.length];
If you want to remove rest of the string after a particular occurrence of "but", you can get the range of "but" and trim the original string down
NSString * test = [NSString stringWithString:#"iphone is good but rest of string"];
NSRange range = [test rangeOfString:#"but"];
if (range.length > 0) {
NSString *adjusted = [test substringToIndex:range.location];
NSLog(#"result %#", adjusted);
}
EDIT
We can assume that the search does not want to cut of "butter is yellow", and can change the range to include " but"
NSRange range = [test rangeOfString:#" but"];
Try this:-
NSArray *array = [string componentsSeperatedBy:#"good"];
NSString *requiredString = [array objectAtIndex:0];
NSArray *array = [string componentsSeparatedByString:stringToSearch];
NSString *requiredString;
if ([array count] > 0) {
requiredString = [[array objectAtIndex:0] stringByAppendingString:stringToSearch];
}

NSString range of string at occurrence

i'm trying to build a function that will tell me the range of a string at an occurrence.
For example if I had the string "hello, hello, hello", I want to know the range of hello at it's, lets say, third occurrence.
I've tried building this simple function, but it doesn't work.
Note - the top functions were constructed at an earlier date and work fine.
Any help appreciated.
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim toChar:(NSUInteger)toCharacterIndex {
if (toCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = 0; i <= toCharacterIndex; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim fromChar:(NSUInteger)fromCharacterIndex {
if (fromCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = (fromCharacterIndex+1); i <= [stringToTrim length]; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSRange)rangeOfString:(NSString *)substring inString:(NSString *)string atOccurence:(int)occurence {
NSString *trimmedString = [inString copy]; //We start with the whole string.
NSUInteger len, loc, oldLength;
len = 0;
loc = 0;
NSRange tempRange = [string rangeOfString:substring];
len = tempRange.length;
loc = tempRange.location;
for (int i = 0; i != occurence; i++) {
NSUInteger endOfWord = len+loc;
trimmedString = [self stringByTrimmingString:trimmedString fromChar:endOfWord];
oldLength += [[self stringByTrimmingString:trimmedString toChar:endOfWord] length];
NSRange tmp = [trimmedString rangeOfString:substring];
len = tmp.length;
loc = tmp.location + oldLength;
}
NSRange returnRange = NSMakeRange(loc, len);
return returnRange;
}
Instead of trimming the string a bunch of times (slow), just use rangeOfString:options:range:, which searches only within the range passed as its third argument. See Apple's documentation.
So try:
- (NSRange)rangeOfString:(NSString *)substring
inString:(NSString *)string
atOccurence:(int)occurence
{
int currentOccurence = 0;
NSRange rangeToSearchWithin = NSMakeRange(0, string.length);
while (YES)
{
currentOccurence++;
NSRange searchResult = [string rangeOfString: substring
options: NULL
range: rangeToSearchWithin];
if (searchResult.location == NSNotFound)
{
return searchResult;
}
if (currentOccurence == occurence)
{
return searchResult;
}
int newLocationToStartAt = searchResult.location + searchResult.length;
rangeToSearchWithin = NSMakeRange(newLocationToStartAt, string.length - newLocationToStartAt);
}
}
You need to rework the whole code. While it may seem to work, it's poor coding and plain wrong, like permanently reassigning the same variable, initializing but reassigning one line later, releasing after returning (which will never work).
For your question: Just use rangeOfString:options:range:, and do this the appropriate number of times while just incrementing the starting point.

NSString character position

NSString *url = #"http://stackoverflow.com/questions/ask";
How can I get the character position of the 4th "/" ?
If you're just trying to get the last part of the url, you should be able to use this:
NSArray* items = [url componentsSeparatedByString:#"/"];
To get the index of the last '/' character:
NSRange range = [url rangeOfString:#"/" options:NSBackwardsSearch];
get the index value from range.location
To find the index of the fourth '/' character from the url:
int count = 0;
int index = -1;
for (unsigned int i=0; i < [url length]; ++i) {
if ([url characterAtIndex:i] == '/') {
++count;
if (count == 4) {
index = i;
break;
}
}
}
Usually you don't have to get the index of the letter /. You can just use many convenience methods defined in NSURL, see this Apple reference. I would do
NSURL* url=[NSURL URLWithString:#"http://stackoverflow.com/questions/ask"];
NSString* last=[url lastPathComponent]; // last is now #"ask"
another way you can use
[url rangeOfString:#"/" options:NSBackwardsSearch].location
hope it help!
I editted my answer after understanding your problem.
The answer of Hitesh it almost correct, you just need to do a little bit more
NSArray* items = [url componentsSeparatedByString:#"/"];
if ([items count] > 4) {
NSString *string = [items objectAtIndex:4];
}