【问题标题】:Replace substring into a string using objective C使用目标 C 将子字符串替换为字符串
【发布时间】:2015-09-23 15:58:44
【问题描述】:

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

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

提前致谢

【问题讨论】:

    标签: arrays string replace substring


    【解决方案1】:

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

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

    或者,如果activeEndpoint 是一个 URL,那就更简单了

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

    【讨论】:

    • 非常感谢。它可以工作,但我得到的 URL 为 http://xx.x.xxx.xx/xx/xx。如何在 http: 之后再插入一个斜杠
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多