How to add an integer into String using objective c? - objective-c

I am a java programmer, I found that Java is very good at doing string.
If I want to do this objective c, how can I do in objective c ?
System.out.println("This is a " + 123 + " test");

To place an integer into a string, you can do this:
int n = 123;
NSString *s = [NSString stringWithFormat:#"This is a %d test", n];
There are numerous other ways. But concatenating strings with integers by + operator is not one of them. :)

To place an integer into a string, you can do this:
int number = 123;
NSString *string = [NSString stringWithFormat:#"This is a %i test", number];
Or if you want to NSLog you have to do this :
int number = 123;
NSLog(#"This is a %i test", number);
It is very EASY !!!

Related

Make a replica of NSString

I want to modify a NSString with reference to other string in Objective C, Can somebody help me.
Example1:
a. "ab cd eg"
b. "ctghml"
I want to change string b like "ct gh ml" , in short want to insert space spaces exactly like string a.
Note: Number of letters will be same like (abcdeg).count = 6 and (ctghml).count = 6
Example2:
a. (abcd) edt-tf
b. (lght)ert-tg
I want to change string b like "(lght) ert-tg" , in short want to insert space spaces exactly like string a.
Note: Number of letters will be same without spaces like ((abcd)edt-tf).count = 12 and ((lght)ert-tg).count = 12
Thanks!
NSString *str1 = #"ab cd eg";
NSMutableString *str2 = [#"ctghml" mutableCopy];
for(int i = 0; i < str1.length; i++) {
unichar c = [str1 characterAtIndex:i];
if (c == ' ') {
[str2 insertString:#" " atIndex:i];
}
}
NSLog(#"%#", str2);

Iterate through variable number of arguments in function without passing nil

I, like many, constantly have to look up date codes for date formatter. I decided to make a file that will make it easier for me to remember them all. I include a function for readability that I declare like this:
NSString * dateFormatString(NSString * string1, ...) {
// Parse out Args
va_list args;
va_start(args,string1);
// Set up our Format String
NSMutableString * formatString = [NSMutableString string];
// Build Format string
for (NSString * arg = string1; arg != nil; arg = va_arg(args, NSString*)) {
[formatString appendString:arg];
}
va_end(args);
return formatString;
}
So, I can then program my NSDateFormatter like this:
dateFormatter.dateFormatString = dateFormatString(DKDayOfWeekFull, #", ", DKMonthNameFull, #" ", DKDayOfMonthComplete, nil);
You could do achieve pretty much the same thing by declaring:
[NSString stringWithFormat:#"%#, %# %#", DKDayOfWeekFull, DKMonthNameFull, DKDayOfMonthComplete];
However, if you're describing a date with more variables like "Sat, Jan 14 2006 at 7:52 AM" it would have to be:
NSString * dateFormatterString = [NSString stringWithFormat:#"%#, %# %# %# 'at' %#:%# %#", DKDayOfWeekAbbreviated, DKMonthNameAbbreviated, DKDayOfMonthComplete, DKYearComplete, DKHour12hrComplete, DKMinutes2Digits, DKAmPm];
Which I personally think is a bit more readable like this:
NSString * dateFormatterString = dateFormatString(DKDayOfWeekAbbreviated, #", ", DKMonthNameAbbreviated, #" ", DKDayOfMonthComplete, #" ", DKYearComplete, #"'at' ", DKHour12hrComplete, #":", DKMinutes2Digits, #" ", DKAmPm, nil);
Question
I would prefer a way to iterate through the variables without having to pass nil into the function. Is there another way to iterate through a variable argument list, other than:
for (NSString * arg = string1; arg != nil; arg = va_arg(args, NSString*)) {
[formatString appendString:arg];
}
I assume you meant to say dateFormatter.dateFormat = ..., since NSDateFormatter has no dateFormatString property.
I assume DKDayOfWeekAbbreviated is a string constant defined as #"E", and DKDayOfWeekFull is #"EEEE", and so on, based on UTS #35.
If that is so, here's a different approach. Define your constants like this:
#define DKDayOfWeekAbbreviated #"E"
#define DKDayOfWeekFull #"EEEE"
#define DKMonthNameFull #"MMMM"
#define DKDayOfMonthComplete #"dd"
Then use compile-time string concatenation to build your strings. The compiler merges two adjacent string constants. For example, "hello " "world" becomes "hello world", and #"hello " #"world" becomes #"hello world". In fact, you can omit the second and later # characters, so #"hello " "world" becomes #"hello world".
Thus:
dateFormatter.dateFormat = DKDayOfWeekFull ", " DKMonthNameFull " " DKDayOfMonthComplete;
You don't need a helper function or varargs.
The only way to support variable arguments using the standard C syntax is to do what you are doing.
But you have another option - use an NSArray.
Your function becomes:
NSString * dateFormatString(NSArray *strings) {
// Set up our Format String
NSMutableString * formatString = [NSMutableString string];
// Build Format string
for (NSString * arg in strings) {
[formatString appendString:arg];
}
return formatString;
}
or simply do:
NSString * dateFormatString(NSArray *strings) {
return [strings componentsJoinedByString:#""];
}
And you call it like this:
dateFormatter.dateFormatString = dateFormatString(#[ DKDayOfWeekFull, #", ", DKMonthNameFull, #" ", DKDayOfMonthComplete ]);
No need for nil using the modern NSArray syntax.

Objective-C: Improve function

I´m new to developing apps and I would like to have some hints about the code I have here:
- (IBAction)button_increase_click:(id)sender {
int number = [self.label_content.text intValue];
number+=1;
NSString *increased_value = [NSString stringWithFormat:#"%d",number];
int count = [increased_value length];
while (count<4) {
increased_value = [NSString stringWithFormat:#"%#%#", #"0",increased_value];
count = [increased_value length];
}
self.label_content.text = increased_value;
}
What I need to do is to increase the value of "label_content" by 1 and fill it with leading zeros until it has reached 4 digits. eg "0001" "0013" "0132".
So how can I improve the above code and take care of its readability?
Thank you for helping me out.
The method can look like this:
- (IBAction)button_increase_click:(id)sender {
int number = [self.label_content.text intValue];
number++;
self.label_content.text = [NSString stringWithFormat:#"%04d", number];
}
Update For increasing readability use camel case for ivar method and other names. It's standard for iOS.
- (IBAction)increaseValue:(id)sender {
int number = [self.contentLabel.text intValue];
number++;
self.contentLabel.text = [NSString stringWithFormat:#"%04d", number];
}
See Apple's String Format Specifiers Documentation.
A better number formatter:
int number = 4;
[NSString stringWithFormat:#"%04d",number];
NSLog(#"number: %04d", number);
NSLog output:
number: 0004

Concatenate integers and strings in Objective C

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?
You can use following code
int iFirst,iSecond;
iFirst=10;
iSecond=20;
NSLog(#"%#",[NSString stringWithFormat:#"%d + %d =%d",iFirst,iSecond,(iFirst+iSecond)]);
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];
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];
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
Check below code :
int i = 8;
NSString * tempStr = [NSString stringWithFormat#"Hello %d",i];
NSLog(#"%#",tempStr);
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.

How to convert from int to string in objective c: example code

I am trying to convert from an int to a string but I am having trouble. I followed the execution through the debugger and the string 'myT' gets the value of 'sum' but the 'if' statement does not work correctly if the 'sum' is 10,11,12. Should I not be using a primitive int type to store the number? Also, both methods I tried (see commented-out code) fail to follow the true path of the 'if' statement. Thanks!
int x = [my1 intValue];
int y = [my2 intValue];
int sum = x+y;
//myT = [NSString stringWithFormat:#"%d", sum];
myT = [[NSNumber numberWithInt:sum] stringValue];
if(myT==#"10" || myT==#"11" || myT==#"12")
action = #"numGreaterThanNine";
If you just need an int to a string as you suggest, I've found the easiest way is to do as below:
[NSString stringWithFormat:#"%d",numberYouAreTryingToConvert]
You can use literals, it's more compact.
NSString* myString = [#(17) stringValue];
(Boxes as a NSNumber and uses its stringValue method)
The commented out version is the more correct way to do this.
If you use the == operator on strings, you're comparing the strings' addresses (where they're allocated in memory) rather than the values of the strings. This is very occasional useful (it indicates you have the exact same string object), but 99% of the time you want to compare the values, which you do like so:
if([myT isEqualToString:#"10"] || [myT isEqualToString:#"11"] || [myT isEqualToString:#"12"])
== shouldn't be used to compare objects in your if. For NSString use isEqualToString: to compare them.
int val1 = [textBox1.text integerValue];
int val2 = [textBox2.text integerValue];
int resultValue = val1 * val2;
textBox3.text = [NSString stringWithFormat: #"%d", resultValue];
Simply convert int to NSString
use :
int x=10;
NSString *strX=[NSString stringWithFormat:#"%d",x];
Dot grammar maybe more swift!
#(intValueDemo).stringValue
for example
int intValueDemo = 1;
//or
NSInteger intValueDemo = 1;
//So you can use dot grammar
NSLog(#"%#",#(intValueDemo).stringValue);