Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode : Count elements in string array

Is there any quick way I can get the number of strings within a NSString array?

NSString *s[2]={@"1", @"2"}

I want to retrieve the length of 2 from this. I there something like (s.size) I know there is the -length method but that is for a string not a string array. I am new to Xcode please be gentle.

like image 307
Vlad Otrocol Avatar asked Feb 23 '12 14:02

Vlad Otrocol


3 Answers

Use NSArray

NSArray *stringArray = [NSArray arrayWithObjects:@"1", @"2", nil];
NSLog(@"count = %d", [stringArray count]);
like image 158
beryllium Avatar answered Nov 15 '22 13:11

beryllium


Yes, there is a way. Note that this works only if the array is not created dynamically using malloc.


NSString *array[2] = {@"1", @"2"}

//size of the memory needed for the array divided by the size of one element.
NSUInteger numElements = (NSUInteger) (sizeof(array) / sizeof(NSString*));

This type of array is typical for C, and since Obj-C is C's superset, it's legal to use it. You only have to be extra cautious.

like image 35
Sulthan Avatar answered Nov 15 '22 13:11

Sulthan


sizeof(s)/sizeof([NSString string]);
like image 33
Rengers Avatar answered Nov 15 '22 14:11

Rengers