Pregunta

Code Snippet:

    NSString *tempStr = self.consumerNumber.text;        

    if ([tempStr hasPrefix:@"0"] && [tempStr length] > 1) {
        tempStr = [tempStr substringFromIndex:1];

        [self.consumerNumbers addObject:tempStr];>           
    }

I tried those things and removing only one zero. how to remove more then one zero

Output :001600240321

Expected result :1600240321

Any help really appreciated

Thanks in advance !!!!!

¿Fue útil?

Solución

Try to use this one

NSString *stringWithZeroes = @"001600240321";

NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:@"^0+" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];

 NSLog(@"Clean String %@",cleanedString);

Clean String 1600240321

Otros consejos

convert string to int value and re-assign that value to string,

NSString *cleanString = [NSString stringWithFormat:@"%d", [string intValue]];

o/p:-1600240321

You can add a recursive function that is called until the string begin by something else than a 0 :

 -(NSString*)removeZerosFromString:(NSString *)anyString
{
    if ([anyString hasPrefix:@"0"] && [anyString length] > 1)
    {
        return [self removeZerosFromString:[anyString substringFromIndex:1]];
    }
    else
        return anyString;
}

so you just call in your case :

NSString *tempStr = [self removeZerosFromString:@"000903123981000"];
NSString *str = @"001600240321";
NSString *newStr = [@([str integerValue]) stringValue];

If the NSString contains numbers only. Other wise use this:

-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
    NSString *newString = string;
    NSInteger count = 0;

    for(int i=0; i<[string length]; i++)
    {
        if([[NSString stringWithFormat:@"%c",[string characterAtIndex:i]] isEqualToString:@"0"])
        {
            newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:@""];
            count++;
        }
        else
        {
            break;
        }
    }
    return newString;
}

Simply call this method:-

NSString *stringWithZeroes = @"0000000016909tthghfghf";
NSLog(@"%@", [self stringByRemovingStartingZeros:stringWithZeroes]);

OutPut: 16909tthghfghf

Try the `stringByReplacingOccurrencesOfString´ methode like this:

NSString *new = [old stringByReplacingOccurrencesOfString: @"0" withString:@""];

SORRY: This doesn't help you due to more "0" in the middle part of your string!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top