使用 objective C 将子字符串替换为字符串

Replace substring into a string using objective C

我正在尝试用现有的 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);

提前致谢

试试这个较短的版本,它会替换该行之后的所有内容 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 的解析交给系统 class 通常会更容易。如果可以,我建议使用 NSURLComponents。例如:

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