-2

我想在从 NSString 出现任何数字(1-9)之前删除所有出现的 0 对

if 000001234000 required 01234000
if 0000123400  required 123400
if 012340000     required 012340000
if 00000012        required 12

任何人都可以帮忙吗?谢谢。

4

6 回答 6

1

也许不是最优雅的解决方案(但只修剪前导'00'):

- (NSString *)trimLeadingDoubleZerosFrom:(NSString *)str {
    if (str.length > 1 ) {
        if ([[str substringWithRange:NSMakeRange(0, 2)] isEqualToString:@"00"]) {
            return [self trimLeadingDoubleZerosFrom:[str substringFromIndex:2]];
        }
    }
    return str;
}

似乎适用于您的示例:

NSLog(@"%@", [self trimLeadingDoubleZerosFrom:@"000001234000"]);// returns 01234000
NSLog(@"%@", [self trimLeadingDoubleZerosFrom:@"0000123400"]);  // returns 123400
NSLog(@"%@", [self trimLeadingDoubleZerosFrom:@"012340000"]);   // returns 012340000
NSLog(@"%@", [self trimLeadingDoubleZerosFrom:@"00000012"]);    // returns 12
NSLog(@"%@", [self trimLeadingDoubleZerosFrom:@"12"]);          // returns 12
NSLog(@"%@", [self trimLeadingDoubleZerosFrom:@"02"]);          // returns 02
NSLog(@"%@", [self trimLeadingDoubleZerosFrom:@"2"]);           // returns 2
于 2013-09-23T13:45:29.407 回答
0
NSString* a = @"00000123";

while ([a hasPrefix:@"00"]) {

    a = [a stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:@""];
}
于 2013-09-23T12:27:08.737 回答
0
NSString *MyString = @"00000123050060007";
NSString *NewString = [self RemovePairOfZero:MyString];
NSLog(@"OUTPUT:: %@", NewString);


- (NSString *)RemovePairOfZero:(NSString *)Param
{
    if ([Param length] > 1 )
    {
        if ([[Param substringWithRange:NSMakeRange(0, 2)] isEqualToString:@"00"])
        {
            return [self RemovePairOfZero:[Param substringFromIndex:2]];
        }
    }
    return Param;
}


//2013-09-24 13:15:58.527 Test[1584:907] OUTPUT:: 0123050060007
于 2013-09-23T12:17:22.883 回答
-1

您可以尝试使用 stringByreplacingOccurancesOfString:@"00" withString:@""

于 2013-09-23T12:12:32.017 回答
-1
NSString *s= @"00000123";

NSLog(@"%@",s);

s = [s stringByReplacingOccurrencesOfString:@"00" withString:@"."];

NSLog(@"%@",s);

试试这个。。

于 2013-09-23T12:21:10.617 回答
-2

这可以通过简单地将@"00" 替换为@"" 来完成

NSString *string = @"00000123";
string = [string stringByReplacingOccurrencesOfString:@"00" withString:@""];

希望有帮助!

于 2013-09-23T12:10:00.323 回答