how to convert NSString to NSInteger - objective-c

I have a NSString(e.g. 'P1')
I have to add 1 in this NSString to get 'P2'.
How will i do this??
Thanks for any help.

You can convert your NSString to an NSInteger like so:
NSInteger myInteger = [[myString substringWithRange:NSMakeRange(1, 1)] integerValue];
In your case if myString was your string P1, myInteger would be 1. So you could then do:
myInteger = myInteger + 1;
Which would then make myInteger 2. To then put that number back after P do:
myString = [NSString stringWithFormat:#"P%i", myInteger];
Now myString is P2.

Split it in to a prefix containing the P and a suffix containing the number. How you do this depends on the possible format of your string.
Then send intValue to the string.
Increment the number
Put it all back together with -stringWithFormat:

Related

how to remove/truncate zero from left side of string

i am trying to remove zero "0" from left in the string means if string is "0000560352"
it will give it to me "560352".
it's dynamically change so if user will enter in textbox like "0560352" then only first zero will remove from string.any idea for this thing.
It is too simple just convert it to NSInteger and then bring back to NSString
NSString *str = #"0000560352";
NSInteger i = [str integerValue];
str = [NSString stringWithFormat:#"%d",i];
You do not need a loop or a conversion
NSCharacterSet *zeros = [NSCharacterSet characterSetWithCharactersInString:#"0"];
NSString *nonLeadingZerosString = [#"000560352" stringByTrimmingCharactersInSet:zeros];
But at the end of the day you want to use a number formatter.

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 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...

Get a long value from an NSString

I need to get a long value from an NSString.
For example, I have this:
NSString *test = #"5437128";
and I need :
long myLong = 5437128;
How I can get this long value from the NSString?
Thank you, it will help me!
long longVariable = [test longLongValue];
See NSString documentation..
Use the NSScanner like in the following code:
unsigned x;
[[NSScanner scannerWithString: s2] scanHexInt: &x];
when typing the scanHexInt stop at scan and see yourself which one you need - there are many possibilities to get values from strings....
You might want to use scanlonglong... having declared your variable as long
use this code :
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
long number = [[numberFormatter numberFromString:string] longValue];
[numberFormatter release];
i use the following in case you don't want to lose the fractions value of your number
double x =[stringValue doubleValue];
instead of
double x = [stringValue longLongValue];
if we assume that we have the following string value
and we want to convert it to double we have 2 ways
NSString * stringValue = #"31.211529225111";
way #1
double x = [stringValue longLongValue];
result will be : x = 31
way #2
double x =[stringValue doubleValue];
result will be : x = 31.211529225111001

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);