Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get length of a nsstring in nsstring that is always 2 digits long?

I am taking the length of a nsstring and converting it to nsstring. I need this last string always 2 digits long, so for example word "hello"'s length in string would be "05" and not "5".

My code so far:

NSString *sth=@"hello";
NSMutableString *result=[NSString stringWithFormat:@"%d", sth.length]; //string is "5" and not "05" that i need
like image 465
DixieFlatline Avatar asked Jan 23 '12 10:01

DixieFlatline


2 Answers

Add .2 after % sign(similar as with floating numbers and decimal part).

    NSString *sth=@"hello";
    NSMutableString *result=[NSString stringWithFormat:@"%.2d", sth.length];
like image 67
Michał Zygar Avatar answered Oct 03 '22 14:10

Michał Zygar


Here is a simple way if I understand your question correctly:

NSString *fish = @"Chips";
NSString *length = [NSString stringWithFormat:@"%02d",[fish length]];
NSLog(@"Chips length is %@",length);

Produces:

2012-01-23 10:42:20.316 TestApp[222:707] Chips length is 05

The 02 means zero pad to length of 2. You will probably want to check that the length of your string is less than 99 characters though.

like image 30
Diziet Avatar answered Oct 03 '22 15:10

Diziet