How to get nsstring length in nsstring, which always consists of two digits?

I take the length of nsstring and convert it to nsstring. I need this last line only 2 digits long, so, for example, the word "hello" length in the line will be "05", not "5".

My code is:

NSString * sth=@ "hello"; NSMutableString *result=[NSString stringWithFormat:@"%d", sth.length]; //string is "5" and not "05" that i need 
+6
source share
3 answers

Add .2 after the% character (similar to floating numbers and decimal).

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

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

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

It produces:

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

02 means zero pad for length 2. You might want to check if your string is less than 99 characters long.

+5
source

Use this

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

Source: https://habr.com/ru/post/906648/


All Articles