iPhone: How to find string in a complete string - iphone

How to get the a certain string from a complete string.
For ex: I have a complete string like below.
"http://serverurl.com/mediadata/Album.wav";
I need to get "Album.wav" from the above string. The name varies with different url string. How to get it?
Thanks.

You could use path components:
NSString fileName = [URLstring lastPathComponent];

You can also use the NSString class methods, those that begin with rangeOfString:
- (NSRange)rangeOfString:(NSString *)aString;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(NSLocale *)locale;

You need to use NSScanner probably and scan up to the 4th slash. whats left after the scan would be the string you want.
Edited
However as with what Richard said if your url isn't going to change a simple path component will work since NSString parses file paths for you. heres an example.
NSArray *urlStrings = [NSArray arrayWithObjects:#"http://serverurl.com/mediadata/Album.wav",
#"http://serverurl.com/mediadata/NewAlbum.wav",
#"http://serverurl.com/mediadata/OtherAlbum.mp3", nil];
for (NSString *url in urlStrings) {
NSLog(#"%#",[url lastPathComponent]);
}
Output
2012-04-15 09:01:15.878 NSScanner[6448:f803] Album.wav
2012-04-15 09:01:15.880 NSScanner[6448:f803] NewAlbum.wav
2012-04-15 09:01:15.881 NSScanner[6448:f803] OtherAlbum.mp3

Related

how to add variable into an url

I am getting userid through parsing a link.Again i have to parse it with userid to get the access.
What i am doing
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/fb_redirect_mobile/?accessToken=4546"];
This gives me the userid,now i want to use that userid to parse it again such as:
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/userid/bookmarks"];
In other languages I have seen they are just using:
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/"+userid+"/bookmarks"];
The userid variable takes user id.how i can do this in iPhone.I know my question is lengthy but i tried to make it clear what i want.please help..please also tell me how to store a parsing id into string,such as userid i am going to get after parsing the url./now how i can save it in form of string.
NSString *userId = #"123456";
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/%#/bookmarks", userId];
initWithFormat:/stringWithFormat: follow the general format convention set by printf/scanf
The way you concatenated your userid is not valid syntax in Obj-C
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/"+userid+"/bookmarks"];
What you'd probably want to do is use a format specifier for an Obj-C object (in your case NSString), and use that within your URL (assuming userid is an NSString, which it probably is. If it's a C based string, use %s as your format specifier instead).
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/%#/bookmarks", userid];
Refer to these on how to use stringWithFormat: on an NSString:
Formatting String Objects
String Format Specifiers
you can give like this,
NSString *str=[NSString stringWithFormat:#"http://abc.com/user/%#/bookmarks",userid];
Instead of
NSString *str=[[NSString alloc]initWithFormat:#"http://abc.com/user/"+userid+"/bookmarks"];
You would use
NSString *str=[[NSString alloc] initWithFormat:#"http://abc.com/user/%#/bookmarks",userid];
Well you almost got it:
NSString *usrid = #"4546";
NSString *str=[NSString stringWithFormat:#"http://abc.com/fb_redirect_mobile/?accessToken=%#", userid];
You can use the stringWithFormat: method of NSString for this.

Unexpected error when trying to use NSLog()

I'm new to iOS develoment, and I'm trying to write an app that can scrape a website (HTML). Scraping google is just an example - I'm planning on scraping something a bit more complex...
My code is as follows:
#import "KppleViewController.h"
#import "TFHpple.h"
#implementation KppleViewController
#synthesize theButton;
- (IBAction)buttonPressed:(UIButton *)sender {
NSLog(#"button Pressed");
NSURL *url = [NSURL URLWithString: #"http://www.google.com"];
NSData *htmlData = [NSData dataWithContentsOfURL: url];
TFHpple *xpathParse = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParse searchWithXPathQuery:#"//h3"];
TFHppleElement *element = [elements objectAtIndex:0];
NSString *h3Tag = [element content];
NSLog(#"x",h3Tag);
}
The problem is that I get an error when I attempt to write to console (via NSLog) to see if anything worked. The error that I get is "Data argument not used by format string"
I've searched all over the internet, to no avail. If I comment out the NSLog to see if I my previous code is correct, I get an error about the variable immediately above the NSlog (h3Tag) declared but not being used.
Any help would be greatly appreciated...
I'm also open to any other methods of scraping HTML...
You're being confused by this line:
NSLog(#"x",h3Tag);
All this line does is log the string x. The second argument is completely unused. What you want is something like this:
NSLog(#"%#", h3Tag);
or perhaps a bit more descriptive:
NSLog(#"h3Tag: %#", h3Tag);
The token %# inside of the format string indicates that this is where the next argument will be printed. You may want to read up on the String Format Specifiers or on Formatting String Objects in general.
use
NSLog(#"%#", h3Tag);
or
NSLog(h3Tag);
NSLog(#"x = %#",h3Tag);
Above line prints the value of h3Tag.
For more help about NSLog refer link: [http://www.cocoadev.com/index.pl?NSLog]

How to selectively trim an NSMutableString?

I would like to know how to selectively trim an NSMutableString. For example, if my string is "MobileSafari_2011-09-10-155814_Jareds-iPhone.plist", how would I programatically trim off everything except the word "MobileSafari"?
Note : Given the term programatically above, I expect the solution to work even if the word "MobileSafari" is changed to "Youtube" for example, or the word "Jared's-iPhone" is changed to "Angela's-iPhone".
Any help is very much appreciated!
Given that you always need to extract the character upto the first underscore; use the following method;
NSArray *stringParts = [yourString componentsSeparatedByString:#"_"];
The first object in the array would be the extracted part you need I would think.
TESTED CODE: 100% WORKS
NSString *inputString=#"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *array= [inputString componentsSeparatedByString:#"_"];
if ([array count]>0) {
NSString *resultedString=[array objectAtIndex:0];
NSLog(#" resultedString IS - %#",resultedString);
}
OUTPUT:
resultedString IS - MobileSafari
If you know the format of the string is always like that, it can be easy.
Just use NSString's componentsSeparatedByString: documented here.
In your case you could do this:
NSString *source = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *seperatedSubStrings = [source componentsSeparatedByString:#"_"];
NSString *result = [seperatedSubStrings objectAtIndex:0];
#"MobileSafari" would be at index 0, #"2011-09-10-155814" at index 1, and #"Jareds-iPhone.plist" and at index 2.
Try this :
NSString *strComplete = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *arr = [strComplete componentsSeparatedByString:#"_"];
NSString *str1 = [arr objectAtIndex:0];
NSString *str2 = [arr objectAtIndex:1];
NSString *str3 = [arr objectAtIndex:2];
str1 is the required string.
Even if you change MobileSafari to youtube it will work.
So you'll need an NSString variable that'll hold the beginning of the string you want to truncate. After that one way could be to change the string and the variable string values at the simultanously. Say, teh Variable string was "Youtube" not it is changed to "MobileSafari" then the mutable string string should change from "MobileSafari_....." to "YouTube_......". And then you can get the variable strings length and used the following code to truncate the the mutable string.
NSString *beginningOfTheStr;
.....
theMutableStr=[theMutableStr substringToIndex:[beginningOfTheStrlength-1]];
See if tis works for you.

writing NSString type to a file

I'm implementing the following function on appdelegate,
but I need to write NSString type instead of typical float values.
Since xcode doesn't allow an object to be in my desired position,
I used char* instead as follows, where as my data to be passed are of type NSString.
As expected, it doesn't work...
How could I manipulate it so that I could write NSString data type?
Should I make some conversion?
Please help me out..
- (void)addHallOfFamer:(char*)newHofer{
[hofArray addObject:[NSString stringWithFormat:#"%#",newHofer]];
[hofArray sortUsingSelector:#selector(compare:)];
NSArray* paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* hofArrayPath = [documentsDirectory
stringByAppendingPathComponent:#"hofers.plist"];
[hofArray writeToFile:hofArrayPath atomically:YES];
}
(added)
following is how I'm calling the written NSStrings from another view, which doesn't reflect my updating.
MainAppDelegate* delegate;
delegate = (MainAppDelegate*)[[UIApplication sharedApplication] delegate];
NSArray *hofers = [[delegate.hofArray reverseObjectEnumerator] allObjects];
hoferName1.text = [NSString stringWithFormat:#"%#",[hofers objectAtIndex:0]];
First, with the current char * argument, you need to use %s as your format directive, not %#.
Second, to use an NSString * as your argument, just add it to hofArray.
The easiest solution would be to just save the array in NSUserDefaults. Since it is an array of strings, saving and retrieving it that way should work fine and would be easier than dealing with the iOS filesystem.
Edit:
If you really want to save it in the filesystem, look into the NSKeyedArchiver method + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path and the NSKeyedUnarchiver method + (id)unarchiveObjectWithFile:(NSString *)path.
Edit 2:
As ondmike pointed out, you need to use %s rather than %# for your -stringWithFormat: method call to work properly. Relevant documentation is String Format Specifiers

How to decoding the string in iphone

I want to decode my string. I have used parsing and get a string from RSS feed. In a string these special characters are not allowed &,<,> in my app. In server side encoding those characters and give it to the string. So now i got the string like,
Actual String : <Tom&Jerry> (only these characters are not allowed in node data & < >).
After Encoding: %3CTom%26Jerry%3E.
But i need to display the string is
<Tom&Jerry>
So how can i decode the string.
Please help me out.
Thanks.
Use the -stringByReplacingPercentEscapesUsingEncoding: method.
[#"%3CTom%26Jerry%3E"
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Look for
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
Or by example:
NSString *input = #"Hello%20World";
NSString *output = [text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%# becomes %#",input,output);
Log: Hello%20World becomes Hello World
I got the answer and my code is,
NSString *currentString =#"%3CTom%26Jerry%3E";
NSString * decodeString = [currentString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
lblTitle.text = decodeString;
Thanks.