4

Please forgive the simplicity of the question. I'm completely new to Objective C.

I'd like to know how to concatenate integer and string values and print them to the console.

This is what I'd like for my output:

10 + 20 = 30

In Java I'd write this code to produce the needed results:

System.Out.Println(intVarWith10 + " + " + intVarWith20 + " = " + result);

Objective-C is quite different. How can we concatenate the 3 integers along with the strings in between?

Zolt
  • 2,761
  • 8
  • 43
  • 60
  • 1
    I'd suggest taking a look at http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings for answers that should point you in the right direction. – Marc Baumbach Jan 14 '13 at 06:39
  • there are plenty of websites with tutorials, have you fired up google? – AndersK Jan 14 '13 at 06:40

6 Answers6

6

You can use following code

int iFirst,iSecond;
iFirst=10;
iSecond=20;
NSLog(@"%@",[NSString stringWithFormat:@"%d + %d =%d",iFirst,iSecond,(iFirst+iSecond)]);
svrushal
  • 1,612
  • 14
  • 25
1

Take a look at NSString - it has a method stringWithFormat that does what you require. For example:

NSString* yString = [NSString stringWithFormat:@"%d + %d = %d",
                              intVarWith10, intVarWith20 , result];
ColinE
  • 68,894
  • 15
  • 164
  • 232
1

You can use C style syntax, with NSLog (If you just need to print)

NSLog(@"%d+%d=%d",intvarWith10,intvarWith20,result);

If you want a string variable holding the value

NSString *str  = [NSString stringWithFormat:@"%d+%d=%d",intvarWith10,intvarWith20,result];
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
1

You have to create an NSString with format and specify the data type.

Something like this :

NSInteger firstOperand=10;
NSInteger secondOperand=20;
NSInteger result=firstOperand+secondOperand;
NSString *operationString=[NSString stringWithFormat:@"%d + %d = %d",firstOperand,secondOperand,result];
NSLog(@"%@",operationString);

NSString with format follows the C printf syntax

Daniel García
  • 612
  • 4
  • 9
0

Check below code :

int i = 8;
NSString * tempStr = [NSString stringWithFormat@"Hello %d",i]; 
NSLog(@"%@",tempStr);
NSCry
  • 1,662
  • 6
  • 23
  • 39
0

I strongly recommend you this link Objective-C Reference.

The Objective-C int data type can store a positive or negative whole number. The actual size or range of integer that can be handled by the int data type is machine and compiler implementation dependent.

So you can store like this.

int a,b;

a= 10; b= 10;

then performing operation you need to first understand NSString.

C style character strings are composed of single byte characters and therefore limited in the range of characters that can be stored.

int C = a + b; NSString *strAnswer = [NSString stringWithFormat:@"Answer %d + %d = %d", a , b, c];

NSLog(@"%@",strAnswer)

Hope this will help you.

Nirav Jain
  • 5,088
  • 5
  • 40
  • 61