text file question - iphone

I have text file that with the following structure:
test\n
1\n
2\n
#/#/#/\n
test2 \n
223\n
44\n
#/#/#/\n
I can read it in array successfuly , but the line #/#/#/ is separator. I want to divide the NSArray to sub arrays at the separator.
Any suggestion how to solve that?
I also need to modify certain section.
Best regards

If you read it in as a NSString then
NSArray *chunks = [string componentsSeparatedByString: #"#/#/#/"];

Use componentsSeparatedByString method.You can store the value obtained in an Array.

Related

importing tyhe csv file in ios sdk

In my app, I am trying to import the csv files as follow:
NSError *error;
NSString *path1=[[NSString alloc]initWithContentsOfFile:CSVPath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#",path1);
NSArray *messArr=[path1 componentsSeparatedByString:#"\n"];
NSLog(#"%#",messArr);
Question:
When i try to log the array, it gives the last column values with many spaces like as follow:
Path1: student_name,gender,email_id
test1,male,a
test2,male,b
test3,male3,c
messArr:
(
"student_name,gender,email_id
",
"test1,male,a
",
"test2,male,b
",
"test3,male3,c"
)
Here i got the count is 4 but can't able to remove spaces.
So, I can't able to remove spaces from the messArr.
Why this happen? I don't know.
Help me to solve this problem.
i think there is a problem with which encoding scheme you used when you creating the csv file.
Thank you,
Please use CSV Parser available on Github repository.
Use CSV parser for Objective-C
Thanks,
you can remove the spaces
by using this meted on each object of messier
NSString *str=[[messArr objectAtIndex:index] stringByTrimmingCharactersInSet: whitespaceAndNewlineCharacterSet];
use this str for your purpose.
I think it is because of \n. if you dont want it then remove this line
NSArray *messArr=[path1 componentsSeparatedByString:#"\n"];
for showing line iterate your array in for loop, & hardcode the \n in the code
for(int i=0; i<[messArr count];i++)
{
NSLog(#"%#\n",[messArr objectAtindex:i]);
}

How to use regular expression in iPhone app to separate string by , (comma)

I have to read .csv file which has three columns. While parsing the .csv file, I get the string in this format Christopher Bass,\"Cry the Beloved Country Final Essay\",cbass#cgs.k12.va.us. I want to store the values of three columns in an Array, so I used componentSeparatedByString:#"," method! It is successfully returning me the array with three components:
Christopher Bass
Cry the Beloved Country Final Essay
cbass#cgs.k12.va.us
but when there is already a comma in the column value, like this
Christopher Bass,\"Cry, the Beloved Country Final Essay\",cbass#cgs.k12.va.us
it separates the string in four components because there is a ,(comma) after the Cry:
Christopher Bass
Cry
the Beloved Country Final Essay
cbass#cgs.k12.va.us
so, How can I handle this by using regular expression. I have "RegexKitLite" classes but which regular expression should I use. Please help!
Thanks-
Any regular expression would probably turn out with the same problem, what you need is to sanitize your entries or strings, either by escaping your commas or by highlighting strings this way: "My string". Otherwise you will have the same problem. Good luck.
For your example you would probably need to do something like:
\"Christopher Bass\",\"Cry\, the Beloved Country Final Essay\",\"cbass#cgs.k12.va.us\"
That way you could use a regexp or even the same method from the NSString class.
Not related at all, but the importance of sanitizing strings: http://xkcd.com/327/ hehehe.
How about this:
componentsSeparatedByRegex:#",\\\"|\\\","
This should split your string whereever " and , appear together in either order, resulting in a three-member array. This of course assumes that the second element in the string is always enclosed in parentheses, and the characters " and , never appear consecutively within the three components.
If either of these assumptions is incorrect, other methods to identify string components may be used, but it should be made clear that no generic solution exists. If the three component strings can contain " and , anywhere, not even a limited solution is possible in such cases:
Doe, John,\"\"Why Unescaped Strings Suck\", And Other Development Horror Stories\",Doe, John <john.doe#dev.null>
Hopefully there is nothing like the above in your CSV data. If there is, the data is basically unusable, and you should look into a better CSV exporter.
The regex you're searching for is: \\"(.*)\\"[ ^,]*|([^,]*),
in ObjC: (('\"' && string_1 && '\"' && 0-n spaces) || string_2 except comma) && comma
NSString *str = #"Christopher Bass,\"Cry, the Beloved Country ,Final Essay\",cbass#cgs.k12.va.us,som";
NSString *regEx = #"\\\"(.*)\\\"[ ^,]*|([^,]*),";
NSMutableArray *split = [[str componentsSeparatedByRegex:regEx] mutableCopy];
[split removeObject:#""]; // because it will print always both groups even if the other is empty
NSLog(#"%#", split);
// OUTPUT:
2012-02-07 17:42:18.778 tmpapp[92170:c03] (
"Christopher Bass",
"Cry, the Beloved Country ,Final Essay",
"cbass#cgs.k12.va.us",
som
)
RegexKitLite will add both strings to the array, therefore you will end up with empty objects for your array. removeObject:#"" will delete those but if you need to maintain true empty values (eg. your source has val,,ue) you have to modify the code to the following:
str = [str stringByReplacingOccurrencesOfRegex:regEx withString:#"$1$2∏"];
NSArray *split = [str componentsSeparatedByString:#"∏"];
$1 and $2 are those two strings mentioned above, ∏ is in this case a character which will most likely never appear in normal text (and is easy to remember: option-shift-p).
The last part looks like it will never contain a comma. Neither will the first one as far as I can see...
What about splitting the string like this:
NSArray *splitArr = [str componentsSeparatedByString:#","];
NSString *nameStr = [splitArr objectAtIndex:0];
NSString *emailStr = [splitArr lastObject];
NSString *contentStr = #"";
for(int i=1; i<[splitArr count]-1; ++i) {
contentStr = [contentStr stringByAppendingString:[splitArr objectAtIndex:i]];
}
This will use the first and last string as is, and combine the rest into the content.
Kind of a hack, but a name and an email address will never contain a comma, right?
Is the title guarantied to have the quotation marks? And is it the only component that can have them? Because then componentSeparatedByString:#"\"" should get you this:
Christopher Bass,
Cry, the Beloved Country Final Essay
,cbass#cgs.k12.va.us
Then use componentSeparatedByString:#"," or substringFrom/ToIndex: to get rid of the two commas in the first and last component.
Here's a solution using substring:
NSString* input = #"Christopher Bass,\"Cry, the Beloved Country Final Essay\",cbass#cgs.k12.va.us";
NSArray* split = [input componentsSeparatedByString:#"\""];
NSString* part1 = [split objectAtIndex:0];
NSString* part2 = [split objectAtIndex:1];
NSString* part3 = [split objectAtIndex:2];
part1 = [part1 substringToIndex:[part1 length] - 1];
part3 = [part3 substringFromIndex:1];
NSLog(part1);
NSLog(part2);
NSLog(part3);

How do you split NSString into component parts?

In Xcode, if I have an NSString containing a number, ie #"12345", how do I split it into an array representing component parts, ie "1", "2", "3", "4", "5"... There is a componentsSeparatedByString on the NSString object, but in this case there is no delimiter...
There is a ready member function of NSString for doing that:
NSString* foo = #"safgafsfhsdhdfs/gfdgdsgsdg/gdfsgsdgsd";
NSArray* stringComponents = [foo componentsSeparatedByString:#"/"];
It may seem like characterAtIndex: would do the trick, but that returns a unichar, which isn't an NSObject-derived data type and so can't be put into an array directly. You'd need to construct a new string with each unichar.
A simpler solution is to use substringWithRange: with 1-character ranges. Run your string through a simple for (int i=0;i<[myString length];i++) loop to add each 1-character range to an NSMutableArray.
A NSString already is an array of it’s components, if by components you mean single characters. Use [string length] to get the length of the string and [string characterAtIndex:] to get the characters.
If you really need an array of string objects with only one character you will have to create that array yourself. Loop over the characters in the string with a for loop, create a new string with a single character using [NSString stringWithFormat:] and add that to your array. But this usually is not necessary.
In your case, since you have no delimiter, you have to get separate chars by
- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange
or this one
- (unichar)characterAtIndex:(NSUInteger) index inside a loop.
That the only way I see, at the moment.
Don't know if this works for what you want to do but:
const char *foo = [myString UTF8String]
char third_character = foo[2];
Make sure to read the docs on UTF8String

NSArray in a Label

I would like to display the contents of the NSMutable array in a label.
I have the following code that displays only the last object. What would be the method to display ALL the objects in the array (in this case "values")?
self.lblMessage.text = [NSString stringWithFormat:#"%#\n%#",
self.lblMessage.text, [values objectAtIndex:[values count]-1]];
Following code should do what you need:
label.numberOfLines = 0; // to make sure your label is able to display multiple lines
label.text = [values componentsJoinedByString:#"\n"]; //insert separator symbol you need in place of "\n"
To get all values in an NSArray joined by a delimiter like ", " use [values componentsJoinedByString:#", "]. The delimiter can of course be "\n" if you like, but you need to make sure your label or textfield supports multiple lines.
Also, your [values objectAtIndex:[values count]-1] can be better expressed as [values lastObject]. :)
Normally a label is only to show one line of text. And you use \n in your code. So there are multiple lines. Delete The \n in your code or try tu use a UITextView. ;-)
There's also a way to force UILabel to display multiple lines, but I don't know that one on the go...

Objective C - Writing an NSString to a plist

I'm writing an NSString to a plist file but after its written to the plist, and when I try to open i get the following message
"This document "mylist.plist" could not be opened XML parser error: Unexpected character 2 at line 1 Old-style plist parser error: Unexpected';' or '=' after key at line 1"
Here is my code:
NSString *temp = [NSString stringWithFormat:#"%#\n Selection is %# \n %d for %.2lf = %.2lf", [NSDate date], #"IPC", 2, 42.34, 2 * 42.34];
[temp writeToFile:[self getPathName:#"mylist.plist"] atomically:YES];
any help would be appreciated.
Thanks,
-[NSString writeToFile...] does not create a plist. It creates a text file. There is no such thing as "writing a string to a plist". Only NSArray and NSDictionary objects can be written to plist files. Those can then contain NSString objects (and other objects, like NSDate and NSData, etc), but what you're asking for is not possible.
For more information, check out the Property List Programming Guide.
Edit: I should clarify what I mean by "creating a plist". When I say that, I'm referring to the XML documents defined by the Apple Plist DTD: http://www.apple.com/DTDs/PropertyList-1.0.dtd
%#\n Selection is %# \n %d for %.2lf = %.2lf is definitely not in any plist format. If you want to retain the plist format, use +[NSPropertyListSerialization dataFromPropertyList:...] to convert the string into data as a plist, then save the data.
And I don't see a reason to use plist if you're only storing 1 string. You can simply save as a .txt and load it using +[NSString stringWithContentsOfFile:...].