从Objective-C中的电话号码的国家/地区代码中删除零

时间:2021-03-05 19:57:52

I want to remove the preceding zeros from phone number's country code. I take it as NSString because phone number contains symbols such as + , ( , ) , - . I need those symbols.

我想从电话号码的国家/地区代码中删除前面的零。我把它当作NSString,因为电话号码包含+,(,), - 等符号。我需要那些符号。

e.g

Input:-

1) NSString *phNo = @"0011234567890";
2) NSString *phNo2 = @"0601234567999";

Output:-

1) 11234567890
2) 601234567999

What I did is as follows

我做了如下

if ([phNo length]>10) {
        NSString *countryCodeSubString = [phNo substringToIndex:[phNo length]-10];
        if ([[countryCodeSubString substringToIndex:1]isEqualToString:@"0"]) {
            for (int i=0; i<[countryCodeSubString length]; i++) {
                NSString *str = [countryCodeSubString substringToIndex:i];
                if ([str isEqualToString:@"0"]) {
                    str = [str stringByReplacingOccurrencesOfString:@"0" withString:@""];
                }

            }
        }
    }

I know above code is wrong. Can anybody help me with this ? How can I do this efficiently ?

我知道上面的代码是错的。任何人都可以帮我吗?我怎样才能有效地做到这一点?

2 个解决方案

#1


2  

int firstNonZeroCharIndex = -1;
for (int i=0; i<phNo.length; ++i) {
    if ([phNo.characterAtIndex:i] != '0') {
        firstNonZeroCharIndex = i;
        break;
    }
}

if (firstNonZeroCharIndex != -1) {
    phNo = [phNo subStringFromIndex:firstNonZeroCharIndex];
}

#2


1  

If you just want to get the preceding zeroes off, then you can do simply like this.

如果你只想关闭前面的零,那么你可以这样做。

NSString *phNo = @"0011234567890";
float number = [phNo floatValue];
NSString *phNoWithOutZero = [NSString stringWithFormat:@"%1.0f", number];

But this will not work it the string have any special characters except number.

但这不会起作用,字符串除了数字之外还有任何特殊字符。

#1


2  

int firstNonZeroCharIndex = -1;
for (int i=0; i<phNo.length; ++i) {
    if ([phNo.characterAtIndex:i] != '0') {
        firstNonZeroCharIndex = i;
        break;
    }
}

if (firstNonZeroCharIndex != -1) {
    phNo = [phNo subStringFromIndex:firstNonZeroCharIndex];
}

#2


1  

If you just want to get the preceding zeroes off, then you can do simply like this.

如果你只想关闭前面的零,那么你可以这样做。

NSString *phNo = @"0011234567890";
float number = [phNo floatValue];
NSString *phNoWithOutZero = [NSString stringWithFormat:@"%1.0f", number];

But this will not work it the string have any special characters except number.

但这不会起作用,字符串除了数字之外还有任何特殊字符。