Searching a word in the NSString - iphone

I am getting a request data and putting it in NSString. after that, I am getting the following string,
_VIEWSTATE=%2FwEPDwULLTE1MjI5NTA5MzBkZBfGgdOVhk6K8WsSgq64ngCpAncw&_EVENTVALIDATION=%2FwEWBgKdhbkbAvOQn7cGApKGyNkMAsKL2t4DApSbgLYHArS6otoP2nSQkmm0E6zJe2u91W5ntimqJ18%3D&x-rim-queue-id=MyOfflineQueue&form_id=723&txt2=siddhesh.b.chavan%40gmail.com&btnSubmit=Submit&x-rim1-request1-title=SignatureShouldBeDoneHere&x-rim-request-title=iPhone3+4%2F6%2F2011+3%3A57%3A21+AM
The thing I have to ask is, I want to get the "form_id" from this string which is "723".
so, How do I get that??
I want to get the form_ID for a request everytime. So, kindly help me out of this.
Thanking you.

These options are more intended for URL arguments parsing, which you are trying to do.
1. Range search : for a word, a character
most efficient but can be fastidious to write... (and read!)
See rangeOfString: and its friends on NSString documentation
2. Split
quick and elegant to write, but not so efficient
Since it is a URL argument style string, it is easily parsable by splitting on & and = witch can be done easily using componentsSeparatedByString: or componentsSeparatedByCharactersInSet:
3. Regular expressions
clean code, powerful
Regular expressions are imho the best choice to manipulate text, but they can be harder to use/learn than previous solutions. To use regular expressions I suggest two options:
iPhone OS >= 3.2 has regular expressions :
NSString rangeOfString:options:NSRegularExpressionSearch
But this is close to option 1.
RegexKitLit, with provides an excellent regular expression engine on OSX/iOS would provide, imho, the best and most powerful solution to your problem (and many others!!!)...
4. Other Kits/API/SDK
the missing api/toolkit/sdk? don't write code thousands people already wrote...
I wished that NSURL would support URL arguments, for parsing and build urls... but it does not.
I don't know a good URL parsing/toolbox library that offers such URL Arguments manipulation tools (Google Toolbox does not provide such URL arguments tools except for escaping which is already really useful) but I'm sure that exists! And a good library, with tested and reliable code would be for sure your best solution...
5. Others... there are many
I forgot to mention NSScanner which I never really looked into (bad me)
More generally, Apple documentation on this topic is interesting.

if you would like to try this: Let me know if it works.
NSInteger formId;
//separate the whole string first by "&" characters
NSArray *array = [myString componentsSeparatedByString:#"&"];
for (NSString *queryString in array)
{
//for every separated string, look if you have the "form_id" key
NSRange range = [queryString rangeOfString:#"form_id=" options:NSLiteralSearch];
if (range.location != NSNotFound)
{
NSLog(#"form_id query string does exist");
//form_id= has 7 characters, pick the character which comes after the "=" sign.
NSString *value = [queryString substringFromIndex:8];
formId = [value integerValue];
}
}
That solution is assuming that you only have 1 "form_id".

Try this :
[myString substringToIndex:index];
[myString substringFromIndex:index];
[myString substringWithRange:range];
Or
if ( [yourString rangeOfString:#"form_id"].location == NSNotFound )
{
NSLog(#"form_id not found");
}

Use 'rangeOfString:options:range:' start by searching the entire string for "form_id=" and then search from where that was found to for an "&". You will need to handle the case where the ampersand isnt found (when form_id is the last in the list).

You can use NSScanner object too. Like-
NSScanner *scanner = [NSScanner scannerWithString:reqData];
[scanner scanUpToString:#"form_id" intoString:nil];
[scanner scanUpToString:#"&" intoString:&strObj];
valueStr = [strObj substringFromIndex:1];

Related

Parse XML in iPhone (attributed not separated)

Is there a way to parse an XML in iOS where the attribute are not separated
e.g:
Users
UserId="1" Name="John Smith" Loc="London"
UserId="2" Name="Johnny Cash" Loc="Nashville"
Users
Thanks
It seams like you havent got xml at all. You are missing all usefully symbols that would normally help with the parsing. You taks is to parse a new format specification.
My first bit of advice is to ask whoever is providing you with this feed to put it into a proper format (JSON or plist are the easiest to work with).
Failing this, if the feed is not too big (otherwise you will hit performance issues), parse the feed manually character by character. You probably want to write a event based parser.
Split the feed line by line, perhaps using componentsSeparatedByString:
Then read characters into a string untill you hit an = that string is your key. Next read between the quotes "" That string is your value. FIre the key and the value off to a delegate.
JSON parsing classes will help you out...
NSString *responseString = #""; // your data contained string.
SBJSON *json = [[SBJSON new] autorelease];
NSArray *resultData = [json objectWithString:responseString error:&error];

problem with unicode in NSString

i have string like: "YouTube - ‪VID 0001‬‏" and i want the string like : YouTube - VID 0001 that means i want to remove the unicodes.
is there a way to remove unicodes like ‪ in iphone apps, if so please help me.
Does this similar question and solution solve your problem?
I'd also recommend heeding the advice given in the comments on the linked question and making sure that you have a valid reason for not wanting unicode.
Try this if you just want to remove the quotes (")
NSString *urString = #"\"YouTube - VID 0001‏\"";
NSString *formattedString = [urString stringByReplacingOccurrencesOfString:#"\"" withString:#""];

How do I localize a string with formatting placeholders?

How do I localize a string that has placeholders in it with NSLocalizedString?
For example:
[NSString stringWithFormat:#"You can afford %i at %#%li.",[kCash integerValue]/self.price, kYen, self.price]
How do I localize this? Do I do break up the strings into multiple localized strings? How then do I deal with varying sentence structure and grammar?
NSLocalizedString won't alter your placeholders, so stringWithFormat can use them as normal. In your example, using numbered placeholders is probably a good idea -
[NSString stringWithFormat:#"You can afford %1$i at %2$#%3$li.",
[kCash integerValue]/self.price, kYen, self.price]
More info here:
Is there a way to specify argument position/index in NSString stringWithFormat?
Have the localized strings include the placeholders. That's pretty much the only proper way to do it as otherwise, as you mentioned, you couldn't take varying word order into account.
Something along these lines:
[NSString stringWithFormat:NSLocalizedString(#"Foo %i", #"Foo %i"), 123]
Another approach to this is in your localized file, you can have:
key = "String with %# placeholder";
and in your implementation:
[NSString stringWithFormat: NSLocalizedString(#"key", ""), #"string replacing placeholder"];
You can do this with any number of arguments, they just need to be consistent across your localization files.
This way seems more efficient:
[NSString stringWithFormat:#"%# %#", NSLocalizedString(#"Key", #"Comment for localised string"), value];

get element value

I have a NSString like that? (in iPhone application)
NSString *xmlStr = "<?xml version=1.0 encoding=UTF-8>
<information>
<name>John</name>
<id>435346534</id>
<phone>045635456</phone>
<address>New York</address>
</information>"
How I can get elements value?
(Do i need convert to XML format and get elements value? or split string? any way please tell me?)
Thank you guys.
If you want to use split string, you can use tokenization of strings using "componentsSeparatedByString" method. This is a more cumbersome method of course, rather than the recommended XMLParser
To get the name.
NSArray *xmlStr_first_array = [xmlStr componentsSeparatedByString: #"<name>"];
NSString *xmlStr_split = [NSString stringWithFormat:#"%#",[xmlStr_first_array objectAtIndex:1]];
NSArray *xmlStr_second_array = [xmlStr_split componentsSeparatedByString: #"</name>"];
NSString *name = [NSString stringWithFormat:#"%#",[xmlStr_second_array objectAtIndex:0]];
The most obvious solution is to use an XML parser to retrieve the values from each element.
You could use the excellent TBXML for this task. It provides a really simple interface where it wouldn't take more than a few lines to retrieve the desired values. The drawback to using this small library is that it (as far as I know) loads the entire XML data into memory. In this particular case, however, that is not problem at all.
There's of course also the option of using the NSXMLParser, though this is an event-driven parser, and thus a bit less simple to use.
Your string is in xml format already and you need to parse it to retrieve data. There're several options available - for example you can use NSXMLParser class or libxml library.
Edit: XMLPerformance sample project shows how to use both approaches and compare their performance.

How do I use comma-separated-values received from a URL query in Objective-c?

How do I use comma-separated-values received from a URL query in Objective-c?
when I query the URL I get csv such as ("OMRUAH=X",20.741,"3/16/2010","1:52pm",20.7226,20.7594).
How do I capture and use this for my application?
You have two options:
Use a CSV parser: http://freshmeat.net/projects/ccsvparse
Or parse the data yourself into an array:
// myString is an NSString object containing your data
NSArray *array = [myString componentsSeparatedByString: #","];
I recently dealt with CSV parsing for Yahoo! Finance as well. I used Ragel to write a parser in C that was good enough for the CSV I was getting. It handled everything but escaped quotes, which are not going to show up much in stock quotes. It was pretty painless and a good learning experience. I'd post the code, but it was work-for-hire, so I don't own it.
Turning a C string into an NSString is easy. If you have it as an NSData, as you likely do at the end of a URL download, just do [[NSString alloc] initWithData:csvData encoding:NSUTF8StringEncoding]. If you have a pointer to a character buffer instead, use [[NSString alloc] initWithBytes:buffer length:buflen encoding:NSUTF8StringEncoding]. buflen could be strlen(buffer) if buffer is a normal, NUL-terminated C string.