Create array of floats from csv Objective C - objective-c

I have once again a beginner problem. I have a CSV file that looks something like this:
3.4,2.4,6.30,2.2,53.42,54,1,5
Now, I have a code that can parse this into an array
NSError *error;
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"csv_file" ofType:#"csv" inDirectory:nil];
NSString *string = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
NSArray *array = [array componentsSeparatedByString:#","];
The issue I have is that I can't do math with these numbers (because they are char - or maybe string, not sure -).
My question is, Is there a way like I did but to create the array with floats, or is there a way to make the strings (or chars) in array into floats.
Thank you, and of course if my question isn't clear just let me know.

Let the elements in the array remain instances of NSString (this is what they are). Just when you access an element from the array make it a float like this:
float f = [array[index] floatValue];
You can't have NSArray of floats in Objective-C because NSArray may contain objects only.

You may be looking for the floatValue property
float sum = 0;
for (NSString *numberString in array) {
sum += [numberString floatValue];
}
If you want to put them in a C array:
float floatArray[array.count];
for(i = 0; i < sizeof(floatArray); i++) {
NSString *numberString = array[i];
floatArray[i] = [numberString floatValue];
}
Note that this way of creating a c array will add it to the stack; you'll need to use malloc if you want to add it to the heap.

Related

Take all numbers separated by spaces from a string and place in an array

I have a NSString formatted like this:
"Hello world 12 looking for some 56"
I want to find all instances of numbers separated by whitespace and place them in an NSArray. I dont want to remove the numbers though.
Whats the best way of achieving this?
This is a solution using regular expression as suggested in the comment.
NSString *string = #"Hello world 12 looking for some 56";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"\\b\\d+" options:nil error:nil];
NSArray *matches = [expression matchesInString:string options:nil range:(NSMakeRange(0, string.length))];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
[result addObject:[string substringWithRange:match.range]];
}
NSLog(#"%#", result);
First make an array using NSString's componentsSeparatedByString method and take reference to this SO question. Then iterate the array and refer to this SO question to check if an array element is number: Checking if NSString is Integer.
I don't know where you are looking to do perform this action because it may not be fast (such as if it's being called in a table cell it may be choppy) based upon the string size.
Code:
+ (NSArray *)getNumbersFromString:(NSString *)str {
NSMutableArray *retVal = [NSMutableArray array];
NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
NSString *placeholder = #"";
unichar currentChar;
for (int i = [str length] - 1; i >= 0; i--) {
currentChar = [str characterAtIndex:i];
if ([numericSet characterIsMember:currentChar]) {
placeholder = [placeholder stringByAppendingString:
[NSString stringWithCharacters:&currentChar
length:[placeholder length]+1];
} else {
if ([placeholder length] > 0) [retVal addObject:[placeholder intValue]];
else placeholder = #"";
return [retVal copy];
}
To explain what is happening above, essentially I am,
going through every character until I find a number
adding that number including any numbers after to a string
once it finds a number it adds it to an array
Hope this helps please ask for clarification if needed

Read from CSV file and create arrays in Objective-C Xcode

I am trying to load a .csv file to Xcode using Objective-C and then I want to create two different arrays. The first array should have values from the first 2 columns and the second array the values of the third column.
I know that what I am looking for is fairly similar to this question, but I am completely newbie in Objective-C and I am a bit confused.
Until now I have tried writing the following code:
NSString* fileContents = [NSString stringWithContentsOfURL:#"2014-07-16_15_41_20.csv"];
NSArray* rows = [fileContents componentsSeparatedByString:#"\n"];
for (int i = 0; i < rows.count; i ++){
NSString* row = [rows objectAtIndex:i];
NSArray* columns = [row componentsSeparatedByString:#","];
}
So, is this piece of code correct until now? Also, how can I divide columns into 2 different arrays in the way I described above?
Your code seems correct. But it's better to use Cocoa Fast Enumeration instead of a for loop with integers.
To divide into arrays your code could look like this.
NSMutableArray *colA = [NSMutableArray array];
NSMutableArray *colB = [NSMutableArray array];
NSString* fileContents = [NSString stringWithContentsOfURL:#"2014-07-16_15_41_20.csv"];
NSArray* rows = [fileContents componentsSeparatedByString:#"\n"];
for (NSString *row in rows){
NSArray* columns = [row componentsSeparatedByString:#","];
[colA addObject:columns[0]];
[colB addObject:columns[1]];
}
Read more about NSMutableArray

Converting NSArray to NSString [duplicate]

This question already has answers here:
Convert NSArray to NSString in Objective-C
(9 answers)
Closed 9 years ago.
I wish to know how to convert an NSArray (for example: ) into an Objective-C string (NSString).
Also, how do I concatenate two strings together? So, in PHP it's:
$variable1 = "string one":
$variable2 = $variable1;
But I need it in Objective-C
Possible duplication: Convert NSArray to NSString in Objective-C
Firstly, that is not PHP concatenation, This is:
$variable1 = "Hello":
$variable1 .= "World";
see: https://stackoverflow.com/a/11441389/1255945
Next, Stackoverflow isnt a personal tutor. You should only post here specific problems and provide as much code and information as you can, not just stuff thats basically saying "I cant be bothered to look myself, tell me".
I must admit I have done this myself so i'm not having a go at you, just trying to be polite as share my knowledge and experience
With that in mind, to convert an NSArray to NSString
Taken from: http://ios-blog.co.uk/tutorials/objective-c-strings-a-guide-for-beginners/
NSString * resultString = [[array valueForKey:#"description"] componentsJoinedByString:#""];
If you want to split the string into an array use a method called componentsSeparatedByString to achieve this:
NSString *yourString = #"This is a test string";
NSArray *yourWords = [myString componentsSeparatedByString:#" "];
// yourWords is now: [#"This", #"is", #"a", #"test", #"string"]
if you need to split on a set of several different characters, use NSString’s componentsSeparatedByCharactersInSet:
NSString *yourString = #"Foo-bar/iOS-Blog";
NSArray *yourWords = [myString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"-/"]
];
// yourWords is now: [#"Foo", #"bar", #"iOS", #"Blog"]
Note however that the separator string can’t be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new string:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
Hope this helps, and Good luck developing :)

string tokenizer in ios

I like to tokenize a string to characters and store the tokens in a string array. I am trying to use following code which is not working as I am using C notation to access the array. What needs to be changed in place of travel path[i]?
NSArray *tokanizedTravelPath= [[NSArray alloc]init];
for (int i=0; [travelPath length]; i++) {
tokanizedTravelPath[i]= [travelPath characterAtIndex:i];
You can't store unichars in an NSArray*. What exactly are you trying to accomplish? An NSString* is already a great representation for a collection of unichars, and you already have one of those.
You need a NSMutableArray to set every element of the array (otherwise you can't change its objects).Also, you can only insert objects in the array, so you can:
- Insert a NSString containing the character;
- Use a C-style array instead.
This is how to do with the NSMutableArray:
NSMutableArray *tokanizedTravelPath= [[NSMutableArray alloc]init];
for (int i=0; i<[travelPath length]; i++)
{
[tokanizedTravelPath insertObject: [NSString stringWithFormat: #"%c", [travelPath characterAtIndex:i]] atIndex: i];
}
I count 3 errors in your code, I explain them at the end of my answer.
First I want to show you a better approach to split a sting into it characters.
While I agree with Kevin that an NSString is a great representation of unicode characters already, you can use this block-based code to split it into substrings and save it to an array.
Form the docs:
enumerateSubstringsInRange:options:usingBlock:
Enumerates the
substrings of the specified type in the specified range of the string.
NSString *hwlloWord = #"Hello World";
NSMutableArray *charArray = [NSMutableArray array];
[hwlloWord enumerateSubstringsInRange:NSMakeRange(0, [hwlloWord length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring,
NSRange substringRange,
NSRange enclosingRange,
BOOL *stop)
{
[charArray addObject:substring];
}];
NSLog(#"%#", charArray);
Output:
(
H,
e,
l,
l,
o,
" ",
W,
o,
r,
l,
d
)
But actually your problems are of another nature:
An NSArray is immutable. Once instantiated, it cannot be altered. For mutable array, you use the NSArray subclass NSMutableArray.
Also, characterAtIndex does not return an object, but a primitive type — but those can't be saved to an NSArray. You have to wrap it into an NSString or some other representation.
You could use substringWithRange instead.
NSMutableArray *tokanizedTravelPath= [NSMutableArray array];
for (int i=0; i < [hwlloWord length]; ++i) {
NSLog(#"%#",[hwlloWord substringWithRange:NSMakeRange(i, 1)]);
[tokanizedTravelPath addObject:[hwlloWord substringWithRange:NSMakeRange(i, 1)]];
}
Also your for-loop is wrong, the for-loop condition is not correct. it must be for (int i=0; i < [travelPath length]; i++)

Creating a NSArray from a C Array

There are many threads about going the opposite way, but I am interested in converting from a primitive C array to a NSArray. The reason for this is that I want to create a NSString from the array contents. To create the NSString I will use:
NSArray *array;
NSString *stringFromArray = [array componentsJoinedByString:#","];
I am joining the elements of the array by commas because I will later be saving the string as a .csv file. I don't think it matters, but the C array I am dealing with is of type double and size 43.
double c_array = new double [43];
Thanks!
NSString * stringFromArray = NULL;
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity: 43];
if(array)
{
NSInteger count = 0;
while( count++ < 43 )
{
[array addObject: [NSString stringWithFormat: #"%f", c_array[count]]];
}
stringFromArray = [array componentsJoinedByString:#","];
[array release];
}