Can anybody please tell me how to put array values[Adding Values] into a string or integer.
Suppose an array a=[1,2,3].
After Adding(+ Action) it should be like
string=1+2+3=>6
Thanks and regards,
Use KVC Collection Operator
NSArray *array =#[#(1),#(2),#(3)];
NSLog(#"Sum is : %#", [array valueForKeyPath:#"#sum.self"]);
Simply loop over your string array and sum it up?!
NSArray *array = #[#"1", #"2", #"3"];
NSInteger sum = 0;
for (NSString *string in array) {
sum += [string integerValue];
}
NSLog(#"%ld", (long)sum);
NSArray *array = #[#1, #2, #3];
int sum = 0;
for (NSNumber * number in array)
{
sum += [number intValue];
}
NSString *result = [NSString stringWithFormat:#"%d", sum];
You can use KVC..
NSNumber *num1 = [NSNumber numberWithInt:1];
NSNumber *num2 = [NSNumber numberWithInt:2];
NSNumber *num3 = [NSNumber numberWithInt:3];
NSArray *arr1= #[num1, num2, num3];
NSString *str = [arr1 valueForKeyPath:#"#sum.intValue"];
NSLog(#"%#",str);
You can use:
NSArray *array = #[#1, #2, #3];
NSInteger sumArray = [[array valueForKeyPath:#"#sum.integerValue"] integerValue];
*I converted the final value to integer, if you don't need then you can replace it by:
NSString *sumArray = [array valueForKeyPath:#"#sum.integerValue"];
It's overkill to use NSArray.
Use plain C array.
int myArray[] = {1,2,3};
int i = 0; int sum= 0;
for (i=0; i < 3; i++){
sum += myArray[i];
}
char str[15];
sprintf(str, "%d", sum);
printf("%s", str);
Related
I have map my data in a NSDictionary. The data is mapped with one key and multiple values.
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
int count = 1;
int intval=111;
int intval2 = 222;
[dict setObject:[NSString stringWithFormat:#"%d,%d",intval,intval2]
forKey#"%d",count];
count++;
How will I fetch both integer value for a key like for key=1? I need to get value 111,222 separately in integer variables.
First thing first you can not addObject(this method is for NSMutableArray) into dictionay, You can setObject or Setvalue for any key.
If you are inserting record same as above and there are two integers separated by comma only than you can get it using below way:
NSString *myBothvalue = [dict valueForKey:#"count"];
NSArray *temp = [myBothvalue componentsSeparatedByString:#","];
NSInteger value1 = [[temp objectAtIndex:0] integerValue];
NSInteger value2 = [[temp objectAtIndex:1] integerValue];
Hope this will help you.
//set object
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
int count = 1; int intval=111; int intval2 = 222;
[dict setObject:[NSString stringWithFormat:#"%d,%d",intval,intval2] forKey:#"count"];
count++;
//Read from dictionary
NSArray *arrayofCount=[[dict valueForKey:#"count"]componentsSeparatedByString:#","];
if(arrayofCount.count>0)
{
int readintval = [[arrayofCount objectAtIndex:0] intValue];
}
if(arrayofCount.count>1)
{
int readintval2 = [[arrayofCount objectAtIndex:1] intValue];
}
I have a sorted array, yrs, which is what it sounds like (a sorted array of years). This array holds 5 objects and each is similar to the object below:
__NSCFNumber * (int)1995 0x79fa3200
I'm trying to subtract the last item from the first item to get the date range:
int first_year = [yrs objectAtIndex:0];
int last_year = [yrs objectAtIndex:4];
NSInteger numberOfCols = ([last_year intValue] - [first_year intValue] ) + 1;
The values of the items in the array are as follows:
first_year int 2078365328 2078365328 where it should be 1995
last_year int 2083083520 2083083520 where it should be
numberOfCols NSInteger 328 328
I honestly have no idea what's going on here.
EDIT
NSMutableArray * years = [NSMutableArray array];
NSMutableArray * atts = [NSMutableArray array];
for(Treatment * treatment in items)
{
NSLog(#"%#",treatment.treatmentMolecule);
NSNumber * startYr = [NSNumber numberWithInt:treatment.startDate.yr];
NSNumber * endYr = [NSNumber numberWithInt:treatment.endDate.yr];
if((![years containsObject:startYr]) && (![startYr isEqual:#0])){
[years addObject:startYr];
}
if((![years containsObject:endYr]) && (![endYr isEqual:#0])){
[years addObject:endYr];
}
}
for(Attack * att in arrayAttack)
{
NSNumber * startYr = [NSNumber numberWithInt:att.yr];
if(![years containsObject:startYr])
[years addObject:startYr];
}
//sort yrs
yrs = [years sortedArrayUsingComparator:(NSComparator)^(NSNumber * yr1, NSNumber * yr2){
return [yr1 compare:yr2];
}];
This is wrong:
int first_year = [yrs objectAtIndex:0];
The element in the array is an instance of NSNumber. Try to replace it with this:
NSNumber *first_year = [yrs objectAtIndex:0];
Even better, you can use firstObject and lastObject instead of hard codes indices.
I would write it like this:
NSNumber *first_year = [yrs firstObject];
NSNumber *last_year = [yrs lastObject];
NSInteger numberOfCols = ([last_year integerValue] - [first_year integerValue] ) + 1;
You should do
int first_year = [[yrs objectAtIndex:0] intValue];
int last_year = [[yrs objectAtIndex:4] intValue];
to get the integer values saved in NSNumber.
I have a problem how to get all integer values from string in Objective-C
NSString *numbers = #"1, 2";
int number = [numbers intValue];
But this just takes the first number (1) but I need both of them.
Thank you guys.
Try something like this:
NSArray *listOfNumbers = [numbers componentsSeparatedByString:#","];
for (NSString *numberAsString in listOfNumbers) {
int number = [numberAsString intValue]; // you might want to trim the string first
}
This is for if they're always separated by a ", ":
NSString *numbers = #"1, 2";
NSArray *numberTokens = [numbers componentsSeparatedByString:#", "];
for (NSString *token in numberTokens) {
NSLog(#"%i", token.integerValue);
}
This solution allows you to specify multiple characters that might separate the numbers:
NSString *numbers = #"1, 2";
NSArray *numberTokens = [numbers componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]];
for (NSString *token in numberTokens) {
if (token.length > 0) {
NSLog(#"%#: %i", token, token.integerValue);
}
}
This may be a simple question, but i don't know the way of doing sorting of array of signed integer values.
My array before sorting,
pointsAry (-2,-7,-5,0,-3,2,-1,-4,1,3,-6)
After using
NSArray * sortedArray = [pointsAry sortedArrayUsingComparator:^(id str1, id str2){
return [(NSString *)str1 compare:(NSString *)str2 options:NSNumericSearch];
}];
Result
sortedArray : (-1,-2,-3,-4,-5,-6,-7,0,1,2,3)
for signed values the sortedArray format is not correct, so i need like
(-7,-6,-5,-4,-3,-2,-1,0,1,2,3)
How to sort like above format ? Thanks in advance.
The following comparator avoids the creation of temporary NSNumber objects:
NSArray *sortedArray = [pointsAry sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
return my_int_compare([str1 intValue], [str2 intValue]);
}];
where
static inline int my_int_compare(int x, int y) { return (x > y) - (x < y); }
is a helper function that compares two integers and returns -1, 0, or +1 (as required
for a comparator method), using the technique from
Is there a standard sign function (signum, sgn) in C/C++?.
Of course the problem only arises because the array contains NSString objects.
Using NSNumbers would be the better solution.
Using the NSNumericSearch option does not help because it does not treat the minus
sign as part of the number.
NSArray *sortedArray = [pointsAry sortedArrayUsingComparator:^(NSString *str1, NSString *str2){
return [#([str1 intValue]) compare:#([str2 intValue])];
}];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"P3",#"P1",#"P4",#"P10", nil];
NSMutableArray *num=[[NSMutableArray alloc]init];
for(int i=0;i<array.count;i++)
{
NSString *str=array[i];
[num addObject: [str substringFromIndex:1]];
}
NSArray *sortedArray = [num sortedArrayUsingComparator:^(NSString *str1, NSString *str2){
return [#([str1 intValue]) compare:#([str2 intValue])];
}];
[array removeAllObjects];
for(int i=0;i<sortedArray.count;i++)
{
NSString *newString = [NSString stringWithFormat:#"P%#",sortedArray[i]];
[array addObject:newString];
}
It's work for me
I have 3 NSMutableArrays k,names,numbers
k array contains {a,b,c,d,e,.....}
names array contains {apple,bag,banana,car,cat,dall,elephant,.....}
numbers array contains {100,200,300,400,500,600,700,...}
All the 3 arrays are dynamic here.
I want to add names[],numbers[] to NSMutableDictionary with k[] as key array..
My output should be like this when i pint that dictionary
a
apple 100
b
bag 200
banana 300
c
car 400
cat 500
d
dall 600
e
elephant 700
Could somebody help me.
thank you.
NSMutableDictionary *result = [NSMutableDictionary new];
for(int i = 0; i<k.count; i++){
unichar letter = [k objectAtIndex:i]; //I'm assuming you have chars in your k array,
// if not, you have to format it here
NSString* name = [names objectAtIndex:i];
if([[name characterAtIndex:0] isEqual:letter]){
NSString *objectToInsert = [NSString stringWithFormat:#"%#: %#", #"name", [numbers objectAtIndex:i]];
[result setObject:objectToInsert forKey:letter];
}
}
You can probably optimize this more, but it should work ;)
Try with following code
NSMutableDictionary *mydic = [[NSMutableDictionary alloc] init];
For(int k = 0; k < firstArray.count ; k++)
{
NSPredicate *pred =[NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", [firstArray objectAtIndex:k]];
NSArray *filteredArr = [MySecodArray filteredArrayUsingPredicate:pred];
NSString *myString = #"";
for (int t = 0 ; t < filteredArr.count ; t ++)
{
myString = [MyThirdArray objectAtIndex:[MySecodArray indexOfObject:[filteredArr objectAtIndex:t]]];
myString = [[filteredArr objectAtIndex:t] stringByAppendingString:myString];
[mydic setValue: myString forKey:[firstArray objectAtIndex:k]];
myString = #"";
}
}
NSLog(#"%#", myDic);
You can do like This,I am assuming nameArry and NumberArray count is same-->
try This code
NSSMutableDictionary *finalDictionary = [[NSSmutableDictionary alloc]init];
for(int i=0;i<k.count;i++)
{
NSString *alphaBet = [k objectAtIndex:i];
//initialize array here
NSMutableArray *insideDictArray = [[NSMutableArray alloc]init];
for(int j=0;j<nameArray.count;j++)
{
NSString *name = [nameArray objectAtIndex:j];
if([name hasPreffix:alphabet])
{
//get Number String
NSString *numberForName = [numberArray objectAtIndex:j];
//Now Concate Number and Name
NSString *concateString = [name stringByAppendingFormat:#"
%#",numberForName];
//Put this in Array we just intialized outside of secondLoop
[insideDictArray addObject:concateString];
}
}
//Now Add array to finalDictionary
[finalDictionary addObject:insideDictArray forKey:alphabet];
}
OutPut Will Be like this i hope :
finalDictionary =
{
a = [aple 100];
b = [bag 200,banana 300];
.
.
}