-1

I want to count how many number of zero(0) before numeric number. Because I need to save those number which is present before numeric.

Exam:- suppose I have a number 0000102. So I want to calculate how many zero(0) before numeric start. In this exam we are see here is 4 zero's(0) are present. It is possible to calculate this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Swarup
  • 11
  • 6

4 Answers4

2
for (i=0;i<string.length;i++) 
 {  
   if ([[string characterAtIndex:i] intValue] <= 9 || [[string characterAtIndex:i] intValue] > 0 )
     {
       i++;
     }
    else
     {
      numerOfZeros++;
     }
}
Neeraj Sonaro
  • 346
  • 1
  • 16
1
int count = 0;
NSString *strr = @"0000102";
unichar findC;
for (int i = 0; i<strr.length; i++)
 {
    findC = [strr characterAtIndex:i];
     if (findC == '0')
          {
           count++;
          }
     else
           break;
  }
 NSLog(@"%d",count);
Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
0

Recursive approach for a one liner:

@implementation NSString (category)

- (NSUInteger)zeroPrefixCount
{
    return [string hasPrefix:@"0"] ? 1 + [[string substringFromIndex:1] zeroPrefixCount] : 0;
}

@end

This is not an optimal solution, performance-wise, but it's typical of your first days at programming classes.

usage

// x will be 4
NSUInteger x = [@"0000102" zeroPrefixCount];
Community
  • 1
  • 1
Cœur
  • 37,241
  • 25
  • 195
  • 267
-1

I recommend you to save this kind of numbers as String itself and no need to further evaluate how many zeros are there rather do a string comparison if needed.

If you really want to count zeros in your number then you can consider converting it to a string and use NSRange and NSString helper methods to get what you want. Similar situation is answered here.

search if NSString contains value

Naveed Abbas
  • 1,157
  • 1
  • 14
  • 37