1

代码片段:

    NSString *tempStr = self.consumerNumber.text;        

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

        [self.consumerNumbers addObject:tempStr];>           
    }

我尝试了这些东西,只删除了一个零。如何删除多于一个零

输出:001600240321

预期结果:1600240321

任何帮助都非常感谢

提前致谢 !!!!!

4

5 回答 5

6

尝试使用这个

NSString *stringWithZeroes = @"001600240321";

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

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

清洁字符串 1600240321

于 2013-07-02T10:05:38.877 回答
4

将字符串转换为 int 值并将该值重新分配给字符串,

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

o/p:-1600240321

于 2013-07-02T10:02:05.957 回答
0

您可以添加一个递归函数,该函数被调用,直到字符串以 0 以外的其他内容开头:

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

所以你只需打电话给你的情况:

NSString *tempStr = [self removeZerosFromString:@"000903123981000"];
于 2013-07-02T10:06:22.570 回答
0
NSString *str = @"001600240321";
NSString *newStr = [@([str integerValue]) stringValue];

如果NSString仅包含数字。其他明智的使用这个:

-(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;
}

只需调用此方法:-

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

输出:16909tthghfghf

于 2013-07-02T10:07:11.043 回答
-1

试试这样的 `stringByReplacingOccurrencesOfString´ 方法:

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

抱歉:这对你没有帮助,因为你的字符串中间部分有更多的“0”!

于 2013-07-02T10:05:33.890 回答