How to split newline from NSString in ObjectiveC - iphone

For my new project. i have loaded my csv file content as a NSString.
First, i need to split this by newline, then split each line by comma.
How can i loop all this? Could you please help me?
CSV Content
"^GSPC",1403.36,"4/27/2012","4:32pm",+3.38,1400.19,1406.64,1397.31,574422720 "^IXIC",3069.20,"4/27/2012","5:30pm",+18.59,3060.34,3076.44,3043.30,0
ViewController.m
NSString* pathToFile = [[NSBundle mainBundle] pathForResource: #"quotes" ofType: #"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
if (!fileString) {
NSLog(#"Error reading file.");
}
NSArray *array = [fileString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for(int i=0; i<[array count]; i++){
//
}

Might want to look into NSMutableArray.
// grab your file
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
for (int i = 0; i < [data count]; i++)
{
[data replaceObjectAtIndex: i
withObject: [[data objectAtIndex: i] componentsSeparatedByString: #","]];
}
Relatedly, Dave DeLong has a proper library to address this need: https://github.com/davedelong/CHCSVParser

Related

How to separate parts of NSString?

I have a NSMutableArray of NSStrings where each element of array has the format equal to #"key is 1::value is 1". Now I want to store string part coming before "::" in an array1 and string part coming after "::" in an array2. How can I do that?
Here is the Code :
NSArray *temp = [YourString componentsSeparatedByString:#"::"];
NSString *str1 = [temp objectAtIndex:0];
NSString *str2 = [temp objectAtIndex:1];
But prior to accessing the Objects in the Array .. check for whether it contains the value.
Try this ::
NSString *s = #"key is 1::value is 1";
NSArray *a = [s componentsSeparatedByString:#"::"];
NSLog(#" -> %# --> %#", [a objectAtIndex:0], [a objectAtIndex:1]);
use this:
[array1 addObject:[[YourString componentsSeparatedByString:#"::"] objectAtIndex:0]];
[array2 addObject:[[YourString componentsSeparatedByString:#"::"] objectAtIndex:1]];
The key to splitting your strings is to use the componentsSeparatedByString: method on NSString to separate your string into an NSArray. Read the docs on how this method acts with blank strings etc, but it's what you'd use.
You said you have an array of strings, so the basic implementation would involve iterating over that array and adding each element to the two other arrays.
NSMutableArray *arrayOfStrings = [NSMutableArray array];
NSMutableArray *array1 = [NSMutableArray array];
NSMutableArray *array2 = [NSMutableArray array];
for (NSString *string in arrayOfStrings)
{
NSArray *components = [string componentsSeparatedByString:#"::"];
if ([components count] == 2)
{
NSString *obj1 = [components objectAtIndex:0];
NSString *obj2 = [components objectAtIndex:1];
[array1 addObject:obj1];
[array2 addObject:obj2];
}
}
I found the way. I will keep adding the beforeString and afterString in array1 and array 2 respectively while iterating the elements of original array
for(int i=0;i<self.originalArray.count;i++)
{
NSString *temp=[self.originalArray objectAtIndex:i];
NSRange r = [temp rangeOfString:#"::"];
NSString *beforeString = [temp substringToIndex:r.location];
NSString *afterString = [temp substringFromIndex:r.location+2];
[array1 addObject:beforeString];
[array2 addObject:afterString];
}

XML Tag xcode save file

I would like to output tags for each line with different tag names and want to save each in a file. I can write the file, but it is over writing. How do I write each and every line in a different file?
Input:
english titanic
leondradicapro kate
German Hotel hüßßan
tomhanks angleina
Output:
<language>english<language/>
<movie>titanic<movie/>
<Actor>leondradiacpro<Actor/>
<Actress>kate<Actress/>
<language>German<language/>
...
Code:
for (NSString *str in lineFile)
{
if([str hasPrefix:#"english "])
{
NSMutableArray *dd = [[NSMutableArray alloc] initWithArray:[[str stringByReplacingOccurrencesOfString:#"english" withString:#""] componentsSeparatedByString:#" "]];
NSArray *tag = [NSArray aarrayWithObjects:#"er",#"langauge",#"movie",#"actor",#"kate",nil];
NSMutableString *output =[[NSMutableString alloc] init];
NSUInteger tagindex =0;
for (NSString *words in word)
{
if(tagindex >=[tag count])
{
NSLog(#"dad");
break;
}
[output appendFormat:#"<%#>%#<%#>\n", [tag objectAtIndex:tagindex],words,[tag objectAtIndex:tagindex]];
NSLog(#"%#",output);
[output writeToFile:#"/Users/xx/Desktop/homework.txt" atomically:YES encoding:NSASCIIStringEncoding error:NULL];
tagindex++;
now i can able to read only the language and movie (1st line) how i can add second line and tag also
you need write file with c method, maybe the following method can help you
-(void)writeToFile:(NSString *)str:(NSString *) fileName
{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *filePath=[NSString stringWithFormat:#"%#",fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
NSLog(#"file not exist,create it...");
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}else {
NSLog(#"file exist!!!");
}
FILE *file = fopen([filePath UTF8String], [#"ab+" UTF8String]);
if(file != NULL){
fseek(file, 0, SEEK_END);
}
int readSize = [data length];
fwrite((const void *)[data bytes], readSize, 1, file);
fclose(file);
}

Comparing with NSMutableArray

In my Array 1, which I loaded images from NSDocumentDirectory, I loaded them and add a NSMutableDictionary:
self.images = [NSMutableArray array];
for(int i = 0; i <= 8; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
[container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:#"image"];
[container setObject:[NSNumber numberWithInt:i] forKey:#"index"];
[images addObject:container];
}
}
In my other array Array 2, I loaded them from the app.
self.images = [NSMutableArray arrayWithObjects:
#"01.jpg",#"02.jpg",#"03.jpg",#"04.jpg",#"05.jpg",#"06.jpg",#"07.jpg",nil];
I was able to add string to Array 2 like this:
for (int x=1; x<8;x++) {
// add as NSString
[images addObject:[NSString stringWithFormat:#"%d", x]];
}
And was able to compare Array 2 like this:
NSInteger index = carousel.currentItemIndex;
if ([[images objectAtIndex:index] intValue] == 1){
What I wanted to do, is to do it to Array 1.
I know Array 1 has been already added with NSNumber, but Im kinda new to NSMutableDictionary so I can't do it the same as Array 2.
Can it be done the same as my Array 2 or what is the other way?
Thanks for the help.
Actually Here you have the array of dictionaries, because you are adding the dictionary which has two objects with keys image and index
So, for retrieving the array of dictionaries,
just log it and see what happens
Edit 2.0
for(int i=0; i< [images count]; i++){
NSNumber *num =[[images objectAtIndex:i] objectForKey:#"index"];
int index = [num intValue];
NSLog(#"%d",index)
}

iPhone - Won’t save array to plist on iPhone

I’m trying to save an array to a .plist file on my iphone but it won’t save to it. When i try it on the simulator it works. But when i run it on the iphone it doesn’t work. I check if the file exists on the device and it does and i can read the data from the file, but it won’t write to it. Here is the code when i add the data to the .plist file.
//Sorts the arrays
[self sortArrays];
NSString *sString = [[NSString alloc] initWithFormat:#"Schema%i", currentIndex];
NSString *daPath = [[NSBundle mainBundle] pathForResource:sString ofType:#"plist"];
NSLog(#"Path: %#", daPath);
//Checks if the file exists
BOOL exists;
NSFileManager *fileManager = [NSFileManager defaultManager];
exists = [fileManager fileExistsAtPath:daPath];
if(!exists)
NSLog(#"PATH %# DOES NOT EXIST", daPath);
else
NSLog(#"PATH %# DO EXIST!!", daPath);
//Writes out the array to check if it gots any elements
for (int i = 0; i < [itemsArray count]; i++)
NSLog(#"%i: %#", i, [(NSMutableArray*)[itemsArray objectAtIndex:i] objectAtIndex:0]);
//Writes the array to the .plist
[itemsArray writeToFile:daPath atomically:YES];
//Gets the .plist file
NSMutableArray *tmpA2 = [[NSMutableArray alloc] initWithContentsOfFile:daPath];
//Checks if the new elements that got added is there.
for (int i = 0; i < [tmpA2 count]; i++)
NSLog(#"FILE: %i: %#", i, [(NSMutableArray*)[tmpA2 objectAtIndex:i] objectAtIndex:0]);
[sString release];
[itemsArray release];
sString = nil;
itemsArray = nil;
Does anyone know why it doesn’t work?
You can not write into the app bundle, you need to write to the app's document directory.
NSString *fileName = #"fileName";
NSArray *searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [searchPath objectAtIndex:0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];
If there is initial data in a file in the app bundle on startup copy it to the document directory if it does not exist and then it can be read, modified and written..

how can I convert string to an array with separator?

I have a string in the following format
myString = "cat+dog+cow"
I need to store each string separated by + in to a array.
Eg:
myArray[0] = cat
myArray[1] = dog
myArray[2] = cow
Can anyone tell me the proper way to do this?
componentsSeparatedByString: splits the string and return the result in an array.
NSArray *myArray = [myString componentsSeparatedByString:#"+"];
[myArray objectAtIndex:0];//cat
[myArray objectAtIndex:1];//dog
[myArray objectAtIndex:2];//cow
Try this..
NSArray *arr = [myString componentsSeparatedByString:#"-"];
[arr objectAtIndex:0];//Hai
[arr objectAtIndex:1];//Welcome
It is vert simple..
NSString * test = #"Hello-hi-splitting-for-test";
NSArray * stringArray = [test componentsSeparatedByString:#"-"];
// Now stringArray will contain all splitted strings.. :)
Hope this helps...
I you don't want use array then iterate through each character...
NSMutableString * splittedString = nil;
for(int i=0;i<test.length;i++){
unichar character = [test characterAtIndex:0];
if (character=='-') {
if (splittedString!=nil) {
NSLog(#"String component %#",splittedString);
[splittedString release];
splittedString = nil;
}
} else {
if (splittedString==nil) {
splittedString = [[NSMutableString alloc] init];
}
[splittedString appendFormat:#"%C",character];
}
}
if (splittedString!=nil) {
NSLog(#"String last component %#",splittedString);
[splittedString release];
splittedString = nil;
}
Thats all...
NSArray *myWords = [myString componentsSeparatedByString:#"+"];
You can find this one very simple
NSString *str = #"cat+dog+cow";
NSArray *arr = [str componentsSeparatedByString:#"+"];
NSLog(#"Array items %#",arr);
OUTPUT:
Array items
(
Cat,
dog,
Cow
)
Use the componentsSeparatedByString: method of NSString.
NSString string = #"hai-welcome";
NSArray myArray = [string componentsSeparatedByString:#"-"];
NSString* haiString = [myArray objectAtIndex:0];
NSString* welcomeString = [myArray objectAtIndex:1];
NSArray *strArray = [myString componentsSeparatedByString:#"-"];
firstString = [strArray objectAtIndex:0];//Hai
secondString = [strArray objectAtIndex:1];//Welcome
This will be the solution if you are dealing with a string:
NSString *mySstring = #"hai-welcome";
NSMutableArray *anArray=[[NSMutableArray alloc] initWithArray:[componentsSeparatedByString: #"-"]];
And each word will be stored in respective position from 0-n.
Try This. :)
If you are averse to using arrays, you can consider this –
NSString *accessMode, *message;
NSScanner *scanner = [NSScanner scannerWithString:#"hai-welcome"];
NSCharacterSet *hyphenSet = [NSCharacterSet characterSetWithCharactersInString:#"-"];
[scanner scanUpToCharactersFromSet:hyphenSet intoString:&accessMode];
[scanner scanCharactersFromSet:hyphenSet intoString:nil];
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:#""] intoString:&message];
NSArray *lines = [string componentsSeparatedByString:#"-"];
The first value will be stored in 0th index of lines and second value will be stored in 1th index of lines..
Why not array?
Simple code :
NSString *myString = [[NSString alloc] initWithString:#"cat+dog+cow"];
NSArray *resultArray = [tempString componentsSeparatedByString:#"+"];
NSLog(#"1. %# 2. %# 3. %#",[resultArray objectAtIndex:0],[resultArray objectAtIndex:1],[resultArray objectAtIndex:2]);
Try This:
NSString *str = #"cat+dog+cow" ;
NSArray *array = [str componentsSeparatedByString:#"+"];
NSLog(#"%#",array) ;