How to split an NSString into multiple NSStrings [duplicate] - objective-c

This question already has answers here:
Is there a simple way to split a NSString into an array of characters?
(4 answers)
Closed 8 years ago.
I'm trying to split an NSString into multiple NSString's. One new string for every character in the NSString. Is there a simpler way to do this than just doing it manually? A method or API that can do this automatically?
For example, turn this string:
_line1 = [NSString stringWithFormat:#"start"];
into:
_string1 = [NSString stringWithFormat:#"s"];
_string2 = [NSString stringWithFormat:#"t"];
_string3 = [NSString stringWithFormat:#"a"];
_string4 = [NSString stringWithFormat:#"r"];
_string5 = [NSString stringWithFormat:#"t"];

The documentation out there is really good. There are lots of ways you could do this.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
One way is to make an array of NSStrings that contain each character.
NSString * line1 = #"start";
NSMutableArray * characters = [NSMutableArray array];
for(int i = 0; i < line1.length; i++) {
NSString * character = [line1.substringWithRange:NSMakeRange(i, 1)];
[characters addObject:character];
}
// Then loop over characters array ...

First off, why are you using _line1? You should never access properties directly via their pointer. Please use self.line1 instead. I will assume you have #property NSString *line1; in your class definition. If not, you'll need to adjust the code I'm posting as necessary.
Second, no there's no way built in. But it's pretty simple to do manually:
NSMutableArray *chars = [NSMutableArray array];
NSUinteger i = 0;
for (i = 0; i < self.line1.length; i++) {
[chars addObject:[self.line1 substringWithRange:NSMakeRange(i, 1)]];
}

Related

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

Create array of floats from csv 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.

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

Neater way to write all these parameters

I have a bunch of saved nsuserdefault parameters that need to be written (20 cars to be exact). I am wondering what will be the neatest way to write this. I number it in order because I believe the for loop will be appropriate(not too sure). The code below represents a snippet of what I am trying to do.
NSString *emailBody=[NSString
stringWithFormat:#"%#, %#, %#",[[NSUserDefaults
standardUserDefaults]stringForKey:#"Car1"],[[NSUserDefaults
standardUserDefaults]stringForKey:#"Car2"],[[NSUserDefaults
standardUserDefaults]stringForKey:#"Car3"]];
There's no reason to save 20 separate items. Just put them in an array and store the array with setObject:forKey:. You can then fetch them all back as an array using stringArrayForKey: (or arrayForKey: or even just objectForKey:).
Once you have an array, creating a comma-separated list is very easy:
NSString *emailBody = [array componentsJoinedByString:#", "];
If you must store them as 20 items for compatibility, I would still pull them out of NSUserDefaults and put them in an array before actually using them.
Just use a for loop, something like this.
NSMutableArray *a = [NSMutableArray array];
for (int i=1;i<21;i++)
{
[a addObject:[NSString stringWithFormat:#"Car%d", i]];
}
Then just put the array into a string.
Slightly neater:
NSMutableString *emailBody = [[NSMutableString alloc] init];
for (unsigned i = 1; i <= 20; i++) {
if (i > 1)
[emailBody appendString:#", "];
[emailBody appendString:[[NSUserDefaults standardUserDefaults]
stringForKey:[StringWithFormat:#"Car%d", i]]];
}

NSString : number of a word [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Number of occurrences of a substring in an NSString?
I would like to know if there's a method which returns the occurrence of a given word.
NSString *string = #"ok no ok no no no ok";
// How to return 4 for the word no ?
Thanks for your help !
use this API: - (NSArray *)componentsSeparatedByString:(NSString *)separator
NSString* stringToSearch = #"ok no ok no no no ok";
NSString* stringToFind = #"no";
NSArray *listItems = [list componentsSeparatedByString:stringToFind];
int count = [listItems count] - 1;
You will get number of occurences of string #"no" in "count" variable
If you are writing a 10.5+ only application, you should be able to use NSString's stringByReplacingOccurrencesOfString:withString: method to do this with fairly minimal code, by checking the length before and after removing the string you're searching for.
Example below (untested as I'm working on 10.4, but can't see why it wouldn't work.) I wouldn't make your application 10.5+ only just to use this though, plenty of other methods suggested by Macmade and in the duplicate question.
NSString* stringToSearch = #"ok no ok no no no ok";
NSString* stringToFind = #"no";
int lengthBefore, lengthAfter, count;
lengthBefore = [stringToSearch length];
lengthAfter = [[stringToSearch stringByReplacingOccurrencesOfString:stringToFind withString:#""] length];
count = (lengthBefore - lengthAfter) / [stringToFind length];
NSLog(#"Found the word %i times", count);
You want to use an NSScanner for this sort of activity.
NSString *string = #"ok no ok no no no ok";
NSScanner *theScanner;
NSString *TARGET = #"no"; // careful selecting target string this would detect no in none as well
int count = 0;
theScanner = [NSScanner scannerWithString:string];
while ([theScanner isAtEnd] == NO)
{
if ([theScanner scanString:TARGET intoString:NULL] )
count++;
}
NSLog(#"target (%#) occurrences = %d", TARGET, count)
;
May not be the fastest way, but you can use the NSString componentsSeparatedByString method to separate your values into an array, and then work with that array to check how many times the string 'no' is contained...
Otherwise, work on a C string ptr, and loop, incrementing the ptr, while using strncmp() or so...