DixieFlatline
DixieFlatline

Reputation: 8035

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

Upvotes: 6

Views: 38957

Answers (3)

Michał Zygar
Michał Zygar

Reputation: 4092

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

    NSString *sth=@"hello";
    NSMutableString *result=[NSString stringWithFormat:@"%.2d", sth.length];

Upvotes: 15

Diziet
Diziet

Reputation: 2417

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.

Upvotes: 6

beryllium
beryllium

Reputation: 29767

Use this

NSMutableString *result=[NSString stringWithFormat:@"%.2d", sth.length];

Upvotes: 0

Related Questions