Accept string values in NSArray from the user - objective-c

hi i want to accept string values into the object of NSArray at run time from the user heres what i tried
-(void)fun
{
NSArray *arr = [[NSArray alloc]init];
for(int i =0;i<3;i++)
{
scanf("%s",&arr[i]);
}
printf("Print values\n");
for(int j =0; j<3;j++)
{
printf("\n%s",arr[j]);
}
}
i am getting an error can you please help me out regarding this and is their any alternative to scanf in objective c.
Thank you

scanf() with a %s format will read the string into a C array, not an NSArray object. You need to read the string into a C array, then make an NSString object to add to your NSArray. You also need to have a mutable array to make your code work. Example:
NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:3];
for (int i = 0; i < 3; i++)
{
char buf[100];
scanf("%s", buf);
NSString *str = [NSString stringWithCString:buf encoding:NSASCIIStringEncoding];
[arr addObject:str];
}
You can use NSLog() to print your strings later on.

use NSMutableArray instead;
than you can use also
[arr addObject:tempVar];

Related

How to convert NSString intoNSArray?

I have an NSString which is a mathematical expression. I have operators (+,-,*,/) and operands (digits from 0 to 9,integers,decimals etc). I want to convert this NSString into NSArray. For example if my NSString is "7.9999-1.234*-9.21". I want NSArray having elements 7.9999,-,1.234,*,-,9.21 in the same order. How can I accomplish this?
I have tried a code. It dosent work in all scenarios though. Here It is:
code:
NSString *str=#"7.9999-1.234*-9.21";
NSMutableArray *marray=[[NSMutableArray alloc] init];
for(i=0;i<6;i++)
{
[marray addObject:[NSNull null]];
}
NSMutableArray *operands=[[NSMutableArray alloc] initWithObjects:#"7.9999",#"1.234",#"9.21",nil];
NSMutableArray *operators=[[NSMutableArray alloc] initWithObjects:#"-",#"*",#"-",nil];
for(i=0,j=0,k=0,l=0;i<=([str length]-1),j<[operands count],k<[operators count],l<[marray count];i++)
{
NSString *element=[[NSString alloc] initWithFormat:#"%c",[str characterAtIndex:i]];
BOOL res=[element isEqualToString:#"+"]||[element isEqualToString:#"-"]||[element isEqualToString:#"*"]||[element isEqualToString:#"/"];
if(res==0)
{
[marray replaceObjectAtIndex:l withObject:[operands objectAtIndex:j]];
}
else
{
l++;
[marray replaceObjectAtIndex:l withObject:[operators objectAtIndex:k]];
k++,l++,j++;
}
}
for(i=0;i<6;i++)
{
NSLog(#"%#",[marray objectAtIndex:i]);
}
Here str is the string to be converted. My array is the array obtained by converting the string str. When I execute this code I get the following on console:
7.9999
-
1.234
*
<null>
-
You should use NSScanner, scanning up to your operator characters, then when you find one, save the scanned string and then save the operator into the array and skip the operator (setScanLocation:). Continue doing this till you get to the end of the string (in a loop, one iteration for each operator).
NSArray * marray = [str componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"+-*/"]
];
ThankYou #Wain and #Hinata Hyuga.I figured out a code that would work to convert any string to array with the help of your suggestions.
Here is the code
NSMutableArray *convArray=[[NSMutableArray alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:inputString];
NSCharacterSet *opSet=[NSCharacterSet characterSetWithCharactersInString:#"+-/*"];
[scanner setCharactersToBeSkipped:opSet];
int i;
for(i=0;i<[inputString length];)
{
if([inputString characterAtIndex:i]=='+'||[inputString characterAtIndex:i]=='-'||[inputString characterAtIndex:i]=='*'||[inputString characterAtIndex:i]=='/')
{
[convArray addObject:[[NSString alloc] initWithFormat:#"%c",[inputString characterAtIndex:i]]];
i++;
}
else
{
NSString *oprnd;
[scanner scanUpToCharactersFromSet:opSet intoString:&oprnd];
[convArray addObject:oprnd];
i=i+[inputString rangeOfString:oprnd].length;
}
}
return convArray;

How to view the entire content of an array in a label (xcode 4.1)

i'm programming in Obj-c with xcode4.1, i have an array with numbers in it, and i want to visualize all of them in a label...can anyone help me around this please?
thanks!
this is the code:
combinedString=[[NSMutableArray alloc] init];
NSString *finalStringLabel=#"";
for (i=0; i<=textLength; i++) {
//character coding
char myChar = [myString characterAtIndex:i];
NSString *myCharS=[NSString stringWithFormat:#"%c", myChar];
int asciiCode=[myCharS characterAtIndex:0];
NSString *asciiS=[NSString stringWithFormat:#"%i", asciiCode];
[combinedString addObject:asciiS];
}
finalStringLabel=[NSString stringWithFormat:#"", [combinedString componentsJoinedByString:#"."]];
myLabel.text=finalStringLabel;
[combinedString release];
}
You can use this
NSArray *yourArray;
NSString *createdString = [yourArray componentsJoinedByString:#" "];
myLabel.text = createdString;
As your array is combinedString,
combinedString=[[NSMutableArray alloc] init];
looks like you are providing values after this line or this is not a property (this is a local as you are releasing it later), and your code in not complete.
Anyways,
You don't need to create an empty string and then assign new object to it, need to do as :
myLabel.text=[combinedString componentsJoinedByString:#"."];
[combinedString release];
}

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];
}

How to append values to an array in Objective-C

I'm doing this:
for(int i=0;i>count;i++)
{
NSArray *temp=[[NSArray alloc]initWIthObjects]i,nil];
NSLog(#"%i",temp);
}
It returns to me 0,1,2,3....counting one by one, but I want an array with appending these values {0,1,2,3,4,5...}.
This is not a big deal, but I'm unable to find it. I am new to iPhone.
NSMutableArray *myArray = [NSMutableArray array];
for(int i = 0; i < 10; i++) {
[myArray addObject:#(i)];
}
NSLog(#"myArray:\n%#", myArray);
This code is not doing what you want it to do for several reasons:
NSArray is not a "mutable" class, meaning it's not designed to be modified after it's created. The mutable version is NSMutableArray, which will allow you to append values.
You can't add primitives like int to an NSArray or NSMutableArray class; they only hold objects. The NSNumber class is designed for this situation.
You are leaking memory each time you are allocating an array. Always pair each call to alloc with a matching call to release or autorelease.
The code you want is something like this:
NSMutableArray* array = [[NSMutableArray alloc] init];
for (int i = 0; i < count; i++)
{
NSNumber* number = [NSNumber numberWithInt:i]; // <-- autoreleased, so you don't need to release it yourself
[array addObject:number];
NSLog(#"%i", i);
}
...
[array release]; // Don't forget to release the object after you're done with it
My advice to you is to read the Cocoa Fundamentals Guide to understand some of the basics.
A shorter way you could do is:
NSMutableArray *myArray = [NSMutableArray array];
for(int i = 0; i < 10; i++) {
[myArray addObject:#(i)];
}
NSLog(#"myArray:\n%#", myArray);