简体   繁体   English

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

[英]Remove Space After a Particular Character in String

I have an string which is coming from a server : 我有一个来自服务器的字符串:

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

I want to remove any space after tel which comes up to 10 characters in the phone number. 我希望删除电话后的任何空格,电话号码中最多10个字符。

I am using the below code for that. 我使用下面的代码。

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

There is code to do this 有代码可以做到这一点

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

Hope it helps :) 希望能帮助到你 :)

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

You can call this with: 您可以这样称呼:

NSString *result = [self removeSpacseFromPhoneNumber:yourString];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM