importing tyhe csv file in ios sdk - iphone

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]);
}

Related

get ascii code from string in xcode for iphone app

hey just a couple quick noob questions about writing my first ios app. Ive been searching through the questions here but they all seem to address questions more advanced than mine so im getting confused.
(1) All I want to do is turn a string into an array of integers representing the ASCII code. In other words, I want to convert:
"This is some string. It has spaces, punctuation, AND capitals."
into an array with 62 integers.
(2) How do I get back from the NSArray to a string?
(3) Also, are these expensive operations in terms of memory or computation time? It seems like it might be if we have to create a new variable at every iteration or something.
I know how to declare all the variables and im assuming I run a loop through the length of the string and at each iteration I somehow get the character and convert it into a number with some call to a built in command.
Thanks for any help you can offer or links to posts that might help!
if you want to store the ascii values in an nsarray it is going to be expensive. NSArray can only hold objects so you're going to have to create an NSNumber for each ASCII value:
unsigned len = [string length];
NSMutableArray arr = [NSMutableArray arrayWithCapacity:len];
for (unsigned i = 0; i < len; ++i) {
[arr addObject:[NSNumber numberWithUnsignedShort:[string characterAtIndex:i]]];
}
2) to go back to an NSString you'll need to use an MSMutableString and append each byte to the NSMutableString.
After saying that I'd suggest you don't use this method if you can avoid it.
A better approach would be to use #EmilioPelaez's answer. To go back from a memory buffer to an NSString is simple and inexpensive compared to iterating and concatting strings.
NSString * stringFromMemory = [[NSString alloc] initWithBytes:buffer length:len encoding: NSASCIIStringEncoding];
I ended up using the syntax I found here. Thanks for the help
How to convert ASCII value to a character in Objective-C?
NSString has a method to get the characters in an array:
NSString *string = "This is some string. It has spaces, punctuation, AND capitals.";
unichar *buffer = malloc(sizeof(unichar) * [string lenght]);
[string getCharacters:buffer range:NSMakeRange(0, [string length])];
If you check the definition of unichar, it's an unsigned short.

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);

text file question

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.

Find words with regEx and then add whitespaces inbetween with Objective-c

I was wondering how to add whitespaces inbetween letters/numbers in a string with Objective-C.
I have the sample code kinda working at the moment. Basically I want to turn "West4thStreet" into "West 4th Street".
NSString *myText2 = #"West4thStreet";
NSString *regexString2 = #"([a-z.-][^a-z .-])";
for(NSString *match2 in [myText2 componentsMatchedByRegex:regexString2 capture:1L]) {
NSString *myString = [myText2 stringByReplacingOccurrencesOfString:match2 withString:#" "];
NSLog(#"Prints out: %#",myString); // Prints out: Wes thStreet // Prints out: West4t treet
}
So in this example, it's replacing what I found in regEx (the "t4" and "hS") with spaces. But I just want to add a space inbetween the letters to separate out the words.
Thanks!
If you wrap parts of your regex patterns in parentheses, you can refer to them as $1, $2, etc in your replacement string (patterns are numbered from left to right, by the order of their opening parenthesis).
NSString *origString = #"West4thStreet";
NSString *newString = [origString stringByReplacingOccurrencesOfRegex:#"(4th)" withString:#" $1 "];
Not sure I understand your broader use case, but that should at least get you going...

iPhone dev: Replace uppercase characters in NSString with space and downcase

I have:
NSString *promise = #"thereAreOtherWorldsThanThese";
which I'm trying to transform into the string:
#"There are other worlds than these"
I'm guessing this is a regex job, but I'm very new to Objective C, and have so far had no luck. I would greatly appreciate any help!
I'd use GTMRegex (http://code.google.com/p/google-toolbox-for-mac/), for example:
NSString *promise = #"thereAreOtherWorldsThanThese";
GTMRegex *regex = [GTMRegex regexWithPattern:#"([A-Z])"];
NSLog(#"%#", [[regex stringByReplacingMatchesInString:promise
withReplacement:#" \\1"] lowercaseString]);
As for removing the uppercase letters you can simply use lowercaseString on NSString.
But as for inserting spaces just before an uppercase letter, I would agree that it would be a job for a regex, and sadly, my regex fu is rubbish :)
Without using any libraries you can use this NSString category I posted. Just perform lowerCaseString on the string array.
How do I convert an NSString from CamelCase to TitleCase, 'playerName' into 'Player Name'?