Question

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.

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 ?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top