使用目标C将子字符串替换为字符串

时间:2015-07-06 13:18:03

标签: arrays string replace substring

我正在尝试用现有的URL IP地址替换我的自定义IP地址。如何用现有IP替换我的IP地址。请找到下面的代码段

 - (IBAction)btnSubmit:(UIButton *)sender {

        NSString *ipAdd = [_txtIPAddress text];
        NSLog(@"My entered IP Address is %@", ipAdd);

        NSLog(@"Current pointing server value is %@", [ConnManager activeEndpoint]);

        NSLog([App appDelegate].isConfigured  ? @"Yes" : @"No");

        NSArray *listItems = [[ConnManager activeEndpoint] componentsSeparatedByString:@"/"];

        ConnManager *conn = [[ConnManager alloc] init];

        NSMutableString *configuredUrl = nil;
        [configuredUrl setString:@""];

        for ( NSInteger i =0; i < listItems.count; i++) {
            if(i != 2) {
                NSMutableString * arrayElement = [(NSMutableString*)listItems objectAtIndex:i];
                NSMutableString *str = [NSMutableString stringWithFormat: @"%@/", arrayElement];
                [configuredUrl appendString:str];
            } else {
                NSMutableString *configstr = [NSMutableString stringWithFormat: @"%@", ipAdd];

                NSLog(@"ConfigString %@", configstr);


//How to replace the my ip address with the array index[2]
 configuredUrl = [configuredUrl stringByAppendingFormat:configstr];
            NSLog(@"Configured Url after apppending %@", configuredUrl);

提前致谢

2 个答案:

答案 0 :(得分:1)

尝试这个较短的版本,它会替换行后的所有内容 NSLog([App appDelegate].isConfigured ? @"Yes" : @"No");

  NSMutableArray *listItems = [[[ConnManager activeEndpoint] pathComponents] mutableCopy];
  listItems[2] = ipAdd;
  NSString *configuredUrl = [NSString pathWithComponents:listItems];
  NSLog(@"%@", configuredUrl);

或者,如果activeEndpoint是网址,则更容易

 NSURL *url = [NSURL URLWithString:[ConnManager activeEndpoint]];
 NSString *configuredURL = [[[NSURL alloc] initWithScheme:[url scheme] host:ipAdd path:[url path]] absoluteString];

答案 1 :(得分:0)

将URL解析为系统类通常更容易。如果可以,我建议使用NSURLComponents。例如:

NSURLComponents *URLComponents = 
     [NSURLComponents componentsWithString:[ConnManager activeEndpoint]];
URLComponents.host = [_txtIPAddress text];
NSString *configuredURL = URLComponents.string;