Xcode : Count elements in string array - objective-c

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.

Use NSArray
NSArray *stringArray = [NSArray arrayWithObjects:#"1", #"2", nil];
NSLog(#"count = %d", [stringArray count]);

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.

sizeof(s)/sizeof([NSString string]);

Tried to search for _countf in objective-c but it seems not existing, so assuming that sizeof and typeof operators works properly and you pass valid c array, then the following may work.
#define _countof( _obj_ ) ( sizeof(_obj_) / (sizeof( typeof( _obj_[0] ))) )
NSString *s[2]={#"1", #"2"} ;
NSInteger iCount = _countof( s ) ;

Related

Objective C Array of Array of Strings

I'm trying to make an array of array of strings so that I can eventually pull out something like ArrayOfArrays[0][1] = "hi".
NSString *ArrayOne[] = {#"hello", #"hi"};
NSString *ArrayTwo[] = {#"goodbye", #"bye"};
NSArray *ArrayOfArrays[] = {#[*ArrayOne, *ArrayTwo]};
However when I try to do this, I get an error: Initializer element is not a compile-time constant.
I've read that this is because I'm creating an array with dynamic values, though it should be static. Not sure how to work around this.
Any advice on making an array of array of strings?
Use NSArray, or rather NSMutableArray if you want to modify it after creation:
NSMutableArray *arrayOne = [#[#"hello", #"hi"] mutableCopy];
NSMutableArray *arrayTwo = [#[#"goodbye", #"bye"] mutableCopy];
NSMutableArray *arrayOfArrays = [#[arrayOne, arrayTwo] mutableCopy];
There are other ways to initialise it, but this is the only way that allows you to use Objective-C literal syntax.
You cannot store plain ol' C arrays within an Objective-C collection class as your code attempts to do.
You wrote:
it should be static
if this is what you want then your use of C arrays is quite valid, you just got the syntax wrong. You can use:
NSString *arrayOfArrays[][2] =
{ {#"hello", #"hi"},
{#"goodbye", #"bye"},
};
Important: The 2 is the number of elements in the inner array, you do not change it when adding further pairs.
This will give you a compile-time static array.
If what you are making is a map from one word to another you might be better off with a dictionary, e.g.:
NSDictionary *wordMap =
#{ #"hello" : #"hi",
#"goodbye" : #"bye"
};
and accessing an element becomes:
wordMap[#"hello"];
Note: the dictionary "constant" here is actually executed code; the C array version can appear as a global or local initialiser, while the dictionary initialisation must be done in a method/function - but it can assign to a global.
HTH
NSArray *array = #[
#[[ #"hello", #"hi" ] mutableCopy],
#[[ #"goodbye", #"bye" ] mutableCopy],
];
NSLog(#"%# is short for %#", array[0][1], array[0][0]);
Output: hi is short for hello

discussing functionality of id's stringValue function?

I got a NSMutableArray object with int values
and I can get a certain value via :
int *v0=[[[arrayObj objectAtIndex:0] intValue];
there is no problem.
But
I got a NSMutableArray object with NSString values
and I cannot get a certain value via :
NSString *v0=[[[arrayObj objectAtIndex:0] stringValue];
//raises error
I want to learn and understand exactly what stringValue for... and why this error occurs ?
NSString *v0=[arrayObj objectAtIndex:0];
works as expected.I asusme its some kind of pointer with null terminated so it can leech value.
Im not sure this line is also unicode/encoded string safe code.
in conclusion:
want to know the purpose of stringValue with some lines o code snippets
I got a NSMutableArray object with int values
That's not possible, Cocoa arrays always contain objects. You probably have an array of NSNumber objects that wrap the integers, like:
NSArray *arrayOfNumbers = #[#1, #2, #3];
NSNumber objects have an intValue method, so this works:
int value = [arrayOfNumbers[0] intValue];
On the other hand when you have an array of strings ...
NSArray *arrayOfStrings = #[#"1", #"2", #"3"];
... you want to access individual elements directly, without converting the string object to something else:
NSString *element = arrayOfStrings[0];
NSString objects do not understand the stringValue method:
[arrayOfStrings[0] stringValue]; // crash: does not recognize selector
Back at the beginning, our NSNumber objects from the first array do understand stringValue. You can use it to convert the number to a string:
NSString *intString = [arrayOfNumbers[0] stringValue];
To make the confusion perfect, NSString also understand the intValue message:
int value = [arrayOfStrings[0] intValue];
Here intValue means to try to convert the string to a plain C int value.
The error you will be getting (but failing to post with your question) will be Unknown selector sent to instance and this is because NSString doesn't have a stringValue method.
The approach you suggest is correct:
NSString *v0 = [arrayObj objectAtIndex:0];
EDIT (prompted by #Answerbot's answer):
The reason you are confused is that [NSString intValue] is used to convert the string value to an integer, as long as the string represents an integer (i.e. #"123"). However you don't need this for string as the object is already a string. It's therefore not provided.

How to append NSString wiht number?

I'm new in Cocoa.
I have NSString - (e.g) MUSIC . I want to add some new NSString in Array,
And want to check something like this
if MUSIC already contained in Array, add Music_1 , after Music_2 and so on.
So I need to be able read that integer from NSString, and append it +1 .
Thanks
Use
NSString *newString = [myString stringByAppendingString:[NSString stringWithFormat:#"_%i", myInteger]];
if myString is "music", newString will be "music_1" or whatever myInteger is.
EDIT: I seem to have gotten the opposite meaning from the other answer provided. Can you maybe clarify what it is you are asking exactly?
Check it out:
NSMutableArray *array = [NSMutableArray arrayWithObjects:#"123", #"qqq", nil];
NSString *myString = #"MUSIC";
NSInteger counter = 0;
if ([array containsObject:myString]){
NSString *newString = [NSString stringWithFormat:#"%#_%d", myString, ++counter];
[array addObject:newString];
}
else
[array addObject:myString];
For checking duplicate element in Array you can use -containsObject: method.
[myArray containsObject:myobject];
If you have very big array keep an NSMutableSet alongside the array.Check the set for the existence of the item before adding to the array. If it's already in the set, don't add it. If not, add it to both.
If you want unique objects and don't care about insertion order, then don't use the array at all, just use the Set. NSMutableSet is a more efficient container.
For reading integer from NSString you can use intValue method.
[myString intValue];
For appending string with number you can use - (NSString *)stringByAppendingString:(NSString *)aString or - (NSString *)stringByAppendingFormat:(NSString *)format ... method.
Here's how you convert a string to an int
NSString *myStringContainingInt = #"5";
int myInt = [myStringContainingInt intValue];
myInt += 1;
// So on...

iPhone - Splitting an NSString into char NSStrings

I've got a 2d NSArray of {{"foo","food only only"}, {"bar","babies are rad"} ... } and I need to end up with 2 NSArrays: one of characters and one of the corresponding words. So #"f", #"o",#"b",#"a",#"r" and #"food",#"only",#"babies",#"are",#"rad" would be my two NSArray's of NSStrings.
So first, how do I get #"f",#"o",#"o" from #"foo"
And second how can I only keep the uniques? I'm guessing NSDictionary and only add if key is not there giving me #"f":#"food" #"o":#"only" then use getObjects:andKeys: to get two C arrays which I'll convert to NSArrays..
Based on the below answer I went with the following. I didn't actually use the NSMutableDict, I just added my letters to it to get the uniqueness check before creating my 2 output arrays:
unichar ch = [[arr objectAtIndex:0] characterAtIndex:i];
NSString *s = [NSString stringWithCharacters: &ch length: 1];
if (![dict objectForKey:s]) {
}
getCharacters will get you started with an array of characters: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/getCharacters:
You could cycle through and check for uniques after
If you want the individual characters of a string, try -characterAtIndex:. That will get you them as the unichar primitive type, which you can then wrap in NSString like so:
unichar ch = ...;
NSString *chString = [NSString stringWithCharacters: &ch length: 1];
To keep uniques, you can store objects in an NSMutableSet, though it will not preserve the order in which objects are added to it.

Easiest way to concatenate NSString and int

Is there a general purpose function in Objective-C that I can plug into my project to simplify concatenating NSStrings and ints?
[NSString stringWithFormat:#"THIS IS A STRING WITH AN INT: %d", myInt];
That's typically how I do it.
Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's appendFormat.
NSMutableString* aString = [NSMutableString stringWithFormat:#"String with one int %d", myInt]; // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:#"... now has another int: %d", myInt];
NSString *s =
[
[NSString alloc]
initWithFormat:#"Concatenate an int %d with a string %#",
12, #"My Concatenated String"
];
I know you're probably looking for a shorter answer, but this is what I would use.
string1,x , these are declared as a string object and integer variable respectively. and if you want to combine both the values and to append int values to a string object and to assign the result to a new string then do as follows.
NSString *string1=#"Hello";
int x=10;
NSString *string2=[string1 stringByAppendingFormat:#"%d ",x];
NSLog(#"string2 is %#",string2);
//NSLog(#"string2 is %#",string2); is used to check the string2 value at console ;
It seems the real answer is no - there is no easy and short way to concatenate NSStrings with Objective C - nothing similar to using the '+' operator in C# and Java.