iphone string replace only the first occurrence with another string - iphone

I have a string in iphone that looks like the following one:
my.whatever.string.with.unknown.length=something whatever something = something .... = whatever
I want to replace only the FIRST "=" with something else.
If I use :
[myString stringByReplacingOccurrencesOfString:#"=" withString:#"somethingHere" ];
It will replace all occurences of "=" . Any suggestions on how to achieve this?

You can use the range argument to specify how far into the string you want it to search. Assuming you can find where the first = is, you can use that to do it. The method definition looks like this:
replaceOccurrencesOfString:withString:options:range:

You can replace string like this..
NSString *mystring=FIRST;
NSString *trimmedString = [mystring stringByReplacingOccurrencesOfString:#" " withString:#""];

Related

remove specific characters from NSString

I wants to remove specific characters or group substring from NSString.
mean
NSString *str = #" hello I am #39;doing Parsing So $#39;I get many symbols in &my response";
I wants remove #39; and $#39; and & (Mostly these three strings comes in response)
output should be : hello I am doing Parsing So i get many symbols in my response
Side Question : I can't write & #39; without space here, because it converted in ' <-- this symbol. so i use $ in place of & in my question.
you should use [str stringByReplacingOccurrencesOfString:#"#39" withString:#""]
or you need replace strings of concrete format like "#number"?
try below code ,i think you got whatever you want simply change the charecterset,
NSString *string = #"hello I am #39;doing Parsing So $#39;I get many symbols in &my response";
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"#39;$&"];
NSString *result = [[string componentsSeparatedByCharactersInSet:trim] componentsJoinedByString:#""];
NSLog(#"%#", result);

Parsing URL Using Regular Expression

I need to parse a URL in the following format:
http://www.example.com/?method=example.method&firstKey=firstValue&id=1893736&thirdKey=thirdValue
All I need is the value of 1893736 within &id=1893736.
I need to do the parsing in Objective-C for my iPhone project. I understand it must have something to do with regular expression. But I just have no clue how to do it.
Any suggestions would be appreciated. :)
You don't need a regex for this. You can try something like this
NSString *url = #"http://www.example.com/?method=example.method&firstKey=firstValue&id=1893736&thirdKey=thirdValue";
NSString *identifier = nil;
for (NSString *arg in [[[url pathComponents] lastObject] componentsSeparatedByString:#"&"]) {
if ([arg hasPrefix:#"id="]) {
identifier = [arg stringByReplacingOccurrencesOfString:#"id=" withString:#""];
}
}
NSLog(#"%#", identifier);
Don't use regular expressions. Use NSURL to reliably extract the query string and then use this answer's code to parse the query string.
Use this:
.*/\?(?:\w*=[^&]*&)*?(?:id=([^&]*))(?:&\w*=[^&]*)*
And grap first group: \1. You will obtain 1893736.
Simplifying
If the id can consist of only digits:
.*/\?(?:\w*=[^&]*&)*?(?:id=(\d*))(?:&\w*=[^&]*)*
If you don't care about capturing uninterested groups (use \3 or id in this case):
.*/\?(\w*=.*?&)*?(id=(?<id>\d*))(&\w*=.*)*
More simpler version (use \3):
.*/\?(.*?=.*?&)*(id=(\d*))(&.*?=.*)*
Instead of using regex, you can split the string representation of your NSURL instance. In your case, you can split the string by the appersand (&), loop the array looking for the prefix (id=), and get the substring from the index 2 (which is where the = ends).

iPhone: Dynamic spaces in NSString

It may be a simple question, but i could't get the answer and needing your help!
I have a string like,
NSString *temp = #"Hello How are you?";
I have to provide spaces dynamically starting in this string by code. For ex: I need to dynamically add 5 spaces in this string in starting point. So, the output string will be like,
#" Hello how are you?"
My doubt is, how can i add spaces dynamically to a existing string? I need it to do this way only, not via any other way like string concatenation etc. due to my requirement.
So, please advise me how can i add spaces dynamically in starting point of the existing string.
Note: The spaces will vary every time, its not constant that i can provide 5 spaces only, it will vary.
Thank you!
An NSString is immutable, so you have to create a new string in any case.
The following code will create a front-padded string with padLength spaces:
int padLength = 10;
NSString* originalString = #"original";
NSString* leadingSpaces = [#"" stringByPaddingToLength:padLength];
NSString* resultString = [NSString stringWithFormat:#"%#%#", leadingSpaces, originalString];

Objective C + Reskit - How do I wrap my dictionary with a key to avoid formatting problems?

I'm trying to wrap my HTTP POST request with a key. In other words, I want to turn this:
{
"category_id"=>"1",
"food_name_token"=>"Pizza",
"id"=>"1"
}
into this:
{
"dish" =>
{
"category_id"=>"1",
"food_name_token"=>"Pizza",
"id"=>"1"
}
}
I tried using the 'rootKeyPath' method in RestKit:
serializationMapping.rootKeyPath = #"dish";
But that gave me this weirdly formatted string :
{
"dish"=>
"{
\n \"category_id\" = 1;
\n \"food_name_token\" = Pizza;
\n id = 1;
\n}
"}
It uses equal signs and semicolons instead of arrows and commas, and adds in all these linebreaks and escape backslashes.
Any idea why? And any suggestions on what I can do instead?
P.S. I'm using a Rails backend
NSDictionary *rootDictionary = [NSDictionary dictionaryWithObject:childDict forKey:#"dish"];
This should solve it.
I found out with Restkit I can wrap attributes using brackets:
[dishMapping mayKeyPath:#"dish[food_name_token]" toAttribute:#"placeToken"];
And this gives me a normal output without the weird formatting.
Add the items into an NSArray, and then add the array into the NSDictionary, like this:
NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:results], #"Parent",nil];
NSLog(#"NSDicitonary %#",item);
NSLog(#"Child values %#",[item valueForKey:#"Parent"]);

How to split a string into sentences cocoa

I have an NSString with a number of sentences, and I'd like to split it into an NSArray of sentences. Has anybody solved this problem before? I found enumerateSubstringsInRange:options:usingBlock: which is able to do it, but it looks like it isn't available on the iPhone (Snow Leopard only). I thought about splitting the string based on periods, but that doesn't seem very robust.
So far my best option seems to be to use RegexKitLite to regex it into an array of sentences. Solutions?
Use CFStringTokenizer. You'll want to create the tokenizer with the kCFStringTokenizerUnitSentence option.
I would use a scanner for it,
NSScanner *sherLock = [NSCanner scannerWithString:yourString]; // autoreleased
NSMutableArray *theArray = [NSMutableArray array]; // autoreleased
while( ![sherLock isAtEnd] ){
NSString *sentence = #"";
// . + a space, your sentences probably will have that, and you
// could try scanning for a newline \n but iam not sure your sentences
// are seperated by it
[sherLock scanUpToString:#". " inToString:&sentence];
[theArray addObject:sentence];
}
This should do it, there could be some little mistakes in it but this is how I would do it.
You should lookup NSScanner in the docs though.. you might come across a method that is
better for this situation.
I haven't used them for a while but I think you can do this with NSString, NSCharacterSet and NSScanner. You create a character set that holds end sentence punctuation and then call -[NSScanner scanUpToCharactersFromSet:intoString:]. Each Scan will suck out a sentence into a string and you keep calling the method until the scanner runs out of string.
Of course, the text has to be well punctuated.
How about:
NSArray *sentences = [string componentsSeparatedByString:#". "];
This will return an array("One","Two","Three") from a string "One. Two. Three."
NSArray *sentences = [astring componentsSeparatedByCharactersInSet:[NSCharacterSet punctuationCharacterSet] ];