在字符串中的特定字符后删除空格

时间:2016-11-29 10:04:15

标签: ios objective-c iphone

我有一个来自服务器的字符串:

<p>Test iOS Contact &nbsp;<a href=\"tel:(945) 369-8563\">(945) 369-8563</a></p>

我想在电话号码后删除任何空格,电话号码最多为10个字符。

我正在使用以下代码。

    if ([serviceMessage containsString:@"tel:"]) {
                NSUInteger location = [serviceMessage rangeOfString:@"tel:"].location + 4;
    serviceMessage = [serviceMessage substringFromIndex:location];
    [serviceMessage substringWithRange:NSMakeRange(11,0)];
    serviceMessage =[serviceMessage substringToIndex:10];
    NSLog(@"New Trimed string:%@",serviceMessage);
    serviceMessage = [serviceMessage stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"Final Trimed string:%@",serviceMessage);
                                        }

2 个答案:

答案 0 :(得分:0)

有代码可以执行此操作

 NSString * serviceMessage = @"<p>Test iOS Contact &nbsp;<a href=\"tel:(945) 369-8563\">(945) 369-8563</a></p>";
NSArray *arr = [serviceMessage componentsSeparatedByString:@":"];

NSString * newStr = [[arr objectAtIndex:1] stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString * updatedString = [NSString stringWithFormat:@"%@%@",[arr firstObject],newStr];

希望有所帮助:)

答案 1 :(得分:0)

-(NSString *)removeSpacseFromPhoneNumber:(NSString *)string
{
    NSString *resultString = @"";
    NSString *phoneIndicatorString = @"tel:";

    NSRange range = [string rangeOfString:phoneIndicatorString];
    if (range.location == NSNotFound) {
        NSLog(@"String does not contain tel:");
        return nil;
    }

    resultString = [string substringToIndex:range.location + phoneIndicatorString.length]; // copy up to and including tel:
    NSString *phoneString = [string substringFromIndex:range.location + phoneIndicatorString.length + 1]; // copy from after tel:
    NSString * convertedPhoneString = [phoneString stringByReplacingOccurrencesOfString:@" " withString:@""];

    return [resultString stringByAppendingString:convertedPhoneString];
}

你可以用以下方式调用:

NSString *result = [self removeSpacseFromPhoneNumber:yourString];