Cut one string into two others in Objective-C - ios

I have an NSURLRequest being made that to a server that returns a string.
string = [[NSMutableString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
receivedData is the mutable array that the downloaded data is stored in. Everything works fine.
I have now, however, added another value to that string. An example of the returned string would be 14587728000000 , 376.99. Originally it was one value so I didn't have to do any splicing. But, now that I have another value, I want to be able to separate it into two different strings.
What should I do to separate the two values into different string? Some kind of search that goes till the first space, or something like that. I have access to the server, and the string is generated in PHP so the separator can be anything.

You can do this with the NSString componentsSeparatedByString method:
NSString *string = #"14587728000000,376.99";
NSArray *chunks = [string componentsSeparatedByString: #","];
You can find some other common NSString tricks (where I found this one) here.

Use -(NSArray *)componentsSeparatedByString: and pass in the token to split by.

Related

Remove Space After a Particular Character

I have an string which is coming from a server :
<p>(555) 555-5555 </p>
I want to remove any space after teland up to 10 characters.
For removing only spaces between characters you can use this
NSString *strNum = #"(555) 555-5555";
strNum = [strNum stringByReplacingOccurrencesOfString:#" " withString:#""];
Hope this will help you..!! :)
Removing spaces is called Trimming. You can find a possible solution here, or here
Solution copied here in case links break :
NSString *string = #" this text has spaces before and after ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
This is slightly better than replacing " " with "", because it uses the charset, and you "never know how white spaces are gonna be in other character sets". The OS does know, so better trust it.
Since your question isn't 100% clear, I'm assuming that is what you need, but feel free to comment for more help :)
EDIT : I might have misunderstood you. If you need to remove all spaces in the string, you could just use Abha's answer.
EDIT 2 : Okay we're about to solve this outstanding mystery.
You want to trim ALL spaces after telinside your string.
What you need to do (and for the sake of learning I'm not gonna write code) is :
Find (using available NSString methods) the word telinside the string. Once you found it, you can find it's index inside the string (after all, a string is just an array of char).
Once you have the index, you just have to use Abha's answer (replace occurences of " " with "") in the range starting with the index you found and ending at that index + 10 (or whatever number you need).
It should be between 2 to 5 lines long, using various NSString methods or, if you really want to, a loop.
Answers you should check for inspiration :
Find string in string
Replace characters in range
Find index of char in string
Though, for the sake of conversation, I'm assuming you only need the phone number (not the tel). So removing ALL spaces should be enough (again, Abha's answer). I don't see any reason why you would take particular care for the first portion of the string when you probably won't use it anyway. Maybe I'm wrong but, you're saying you're new and I'm thinking you're approaching this the wrong way.
Also, to add something else, if you have any control over the server, the server itself should not send tel:(555) 555 5555. That's prone to mistakes. Either the server sends a string to be displayed, with proper characters and nice writing, like Telephone : (555) 555 5555", or you receive ONLY the phone number in a phone object (json or something), like 5555555555. If you have any control over the server, make it send the correct information instead of sending something not practical and having to rework it again.
Note that usually, it's the second option. The server sends something raw, and you just modify it to look good if necessary. Not the other way around.
You need to use NSMutableString class and its manipulation functions provided itself.
NSMutableString *muString = [NSMutableString stringWithString:#"(555) 555-5555"];
[muString insertString:#"" atIndex:10];
Some methods to split your string :
substringFromIndex:
substringWithRange:
substringToIndex:
Edit:
If your string is dynamic and you really dont know the index from where you need to remove extra spaces use below method of NSString class:
stringByReplacingOccurrencesOfString: Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
Example:
NSString *yourStr = #"(555) 555-5555"; // needs to remove spaces and all
yourStr = [yourStr stringByReplacingOccurrencesOfString:#" " withString:#""]; // after manipulation
Or if you really need to do some more advance changes into your string use NSMutableString class see detail below and example above on the top:
NSMutableString: The NSMutableString class declares the programmatic interface to an object that manages a mutable string—that is, a string whose contents can be edited—that conceptually represents an array of Unicode characters. To construct and manage an immutable string—or a string that cannot be changed after it has been created—use an object of the NSString class.
So you want to remove space from first 10 character, which you think is a tel number, right?
So make a sub string and replace space from that.
NSString *str = #"(555) 555-5555";
NSString *firstPart = [[str substringToIndex:10] stringByReplacingOccurrencesOfString:#" " withString:#""];
then take the second part and merge it.
NSString *secondPart = [str substringFromIndex:10];
NSMutableString *finalString = [NSMutableString stringWithFormat:#"%#%#",firstPart,secondPart];
Is this what you want to do? I've written in step by step for better understanding.
This solution in not generic but may work on your condition
NSString * serverString;
NSArray* stringComp = [serverString componentsSeparatedByString:#"\\"];
NSString* stringOfTel = [stringComp objectAtIndex:1];
NSString* withOutSpaceTel = [stringOfTel stringByReplacingOccurrencesOfString:#" " withString:#""];
serverString = [serverString stringByReplacingOccurrencesOfString:stringOfTel withString:withOutSpaceTel];
and your will get your serverstring with space you want.
Again this may work only for your current solution.
NSString *string = #"(555) 555-5555" //here you need to assign string which you are getting from server
NSString *resultString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
resultString will be the string with no space at start and end of the string.
Hope this helps!

split string in ios string from json data?

I have one string. Now I wanted to split this string. For static separation I know the code but I don’t code for dynamic value.
my string is
NSString *str = #"https://graph.facebook.com/v2.5/181054825200000/feed?fields=created_time,message,picture,full_picture,comments.limit%280%29.summary%28true%29,likes.limit%280%29.summary%28true%29&limit=5&format=json&access_token=CAALjFrE5mNYBAOg1EDiUrsE2kr1kIRrLIv7g4OweSMvHso2exB5Dttshn7dgOlW24ZCXSnDZAWiV6xMUKXedTXUhiHpdmZBPCGzD1orFlrLRP2gaBZCbZBZBnjUHewF9hZBmJKxtiwVzpw9gnnQXk5Hfx0ZBM2ksAUzkSWR5feaNMbf3UUmUpJlxeh0gKdDrzWBvIJRPy0xGqL0ZAMFsRhyCZCTX42l1sZAceZB0VCeDZB95mrAZDZD&until=1456345291&__paging_token=enc_AdCKD3tSYMoZB3MCKaJkYnbVmBgUyY2tBceGDD2G1hqxRDiQKZCsSbmvWZASLvlCMf0BVzq2uZAScSWp7ZAavZB2d72BIHJISefk09noRuv9gA5b5hFwZDZD";
but i don’t how to show any value dynamically .(for e.g. until (in string))
please help me for this issue.
Thank You.
If you are parsing a URL you should really use NSURLComponents. It makes breaking a URL into the different parts much easier, and the code is tested and verified by Apple.
For separate string by a separator you can use this.
NSString *url = #"<url>";
NSArray *array = [url componentsSeparatedByString:#"<seperator string>"];
NSLog(#"%#", array);
But for URL parsing ,As per Duncan's answer, yes it is good to parse a URL using NSURLComponents. By using this class you can get any desired part of an URL.

Clarification on NSString methods

I would like to get a clarification/difference on the NSString declaration. Consider the following codes:
NSString *str = #"string";
NSString *str = [NSString stringWithFormat:#"string"];
NSString *str = [[NSString alloc] initWithString:#"string"];
Can anyone help me to understand the difference between the above three type of string declaration? Does the difference come in terms of memory or will there be any other reasons? I have gone through various posts to understand the difference, but I couldn't understand the exact difference.
Sree
Edit (thanks for the comments):
Using ARC, the first statement is used by the compiler to create a string that is accessible during the lifetime of the app and never deallocated.
The last two statements produce the same kind of string.
Using manual memory management, the second statement produces an autoreleased string.
The last produces a retained string. This means, when using the last statement, you would have to add a release later in the code.
for: NSString *str = #"string"; used when you use as a static string .
for Exmple.
int abc=5;
for: NSString *str = [NSString stringWithFormat:#"%d",abc]; used when you convert your integer or float into string.
for: NSString *str = [[NSString alloc] initWithString:#"string"]; used when above same same reason but only difference is you alloc string and then passes static string.
but in ARC no need to alloc string.
as I remember in this case
NSString *str = #"string";
the memory for the string will be allocated once and will be reused for all same strings in whole application. Something like global constant.
https://en.wikipedia.org/wiki/String_literal
There is the proof: "Objective-C string constant is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated"
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html
The others 2 is the same, also you can formate string with stringWithFormat method: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html#//apple_ref/doc/uid/20000943
NSString literal
#"string"
This will make the compiler emit a statically allocated NSString instance. The object itself will never be deallocated (release is a no-op).
Unique instance from format
[NSString stringWithFormat:#"string"]
Here the string is created from parsing and transforming the format string. This involves runtime overhead and returns an autoreleased instance.
Initialize by copying a literal
[[NSString alloc] initWithString:#"string"]
This will (1) create the literal, (2) allocate a default string, (3) throw away the default string, (4) call copy on the literal, and (5) return the result (again, the literal, because copy just returns it). The logic retain count is +1 (automatically handled by ARC).

Write content of NSURL to an array

I have a program that retrieves data from a link and i write it out to the Log like this.
NSURL *getURL=[NSURL URLWithString:#"link.php"];
NSError *error=nil;
NSString *str=[NSString stringWithContentsofURL:getURL encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%",str);
This prints to the log the three values from my php as expected.
However I am having a little difficulty saving this in an array which then displays it those values in a UISplitviewController (the leftcontroller side).
which is written like this
showArray=[[NSMutableArray alloc]initWithContentofURL:getURL];
then in cellForRowAtIndexPath: method is
cell.textLabel.text=[showArray object atIndex:indexPath.row];
A second thing i have tried is write myURL to an array and tried to initlize showArray with ContentsofArray like this
NSArray *retults=[NSArray arraywithContentsOFURL:getURL];
showArray=[[NSArray alloc]initWithArray:retults];
but THAT dont work
BUT if i say
showArray=[[NSMutableArray alloc]initWithObjects:#"One",#"Two",nil];
One and two shows in my leftview controller....
Would love is someone could help me with this...Thank you
Are you trying to add the contents of the URL or the URL itself ?
If you are trying to just add the URL, then use :
showArray = [#[getURL] mutableCopy];
However, if you are trying to add the contents of the URL, then the doc clearly states that the URL must represent a string representation of an array.
Furthermore :
Returns nil if the location can’t be opened or if the contents of the location can’t be parsed into an array.
EDIT :
I saw your comment on your post and your data looks like JSON data.
You should take a look at the NSJSONSerialisation class which is pretty straightforward to use (you'll find lots of example here on SO).
U have done web services perfectly, now wat u have to do is parse it to an array
First download the SBJSON files in this link
https://github.com/stig/json-framework/
Then, copy them to your workspace.
Then, in the viewController add this
#import "SBJson.h"
Your JSON data contains values in the form of dictionary
SO, to parse them
SBJsonParser * parser=[SBJsonParser new];
NSDictionary * jsonData=(NSDictionary *)[parser objectWithString:outputData];
NSArray * arr=(NSArray *)[NSDictionary objectForKey:#"animal"];
I think this will help

iOS Conversion from a dictionary to a NSString

I have a NSMutableDictionary holding EXIF metadata from a picture.
An example:
const CFStringRef kCGImagePropertyExifExposureTime;
Instead of accessing every key individually, I just want write the whole dictionary content into a label.
When I want to write this data into the console I would just use:
NSLog(#"EXIF Dic Properties: %#",EXIFDictionary );
That works fine, but if I use:
NSString *EXIFString = [NSString stringWithFormat:(#"EXIF Properties: %#", EXIFDictionary)];
I get warnings that the result is not a string literally and if I try to use that string to set my label.text, the program crashes.
Any idea where my error is?
[NSString stringWithFormat:(#"EXIF Properties: %#", EXIFDictionary)] is not, as you may think, a method with two arguments. It's a method with one argument. That one argument is (#"EXIF Properties: %#", EXIFDictionary), which uses the comma operator and ends up returning EXIFDictionary. So in essence you have
[NSString stringWithFormat:EXIFDictionary]
which is obviously wrong. This is also why you're getting a warning. That warning tells you that the format argument is not a string literal, because using variables as format strings is a common source of bugs. But more importantly here, that argument isn't even a string at all, and so it crashes.
Remove the parentheses and everything will be fine. That will look like
[NSString stringWithFormat:#"EXIF Properties: %#", EXIFDictionary];
I get warnings that the result is not a string literally
Nah. You get a warning saying that the format string of stringWithFormat: is not a string literal. That's because you don't know how the comma operator (and a variadic function) works (that's why one should master the C language before trying to make an iOS app). Basically what you have here:
[NSString stringWithFormat:(#"EXIF Properties: %#", EXIFDictionary)]
is, due the behavior of the comma operator, is equivalent to
[NSString stringWithFormat:EXIFDictionary]
which is obviously wrong. Omit the parentheses, and it will be fine:
[NSString stringWithFormat:#"EXIF Properties: %#", EXIFDictionary]
You don't want those parentheses:
NSString *EXIFString = [NSString stringWithFormat:#"EXIF Properties: %#", EXIFDictionary];

Resources