English 中文(简体)
目标C: 如何从国家统计部门中提取替代物?
原标题:Objective-C: Best way to extract substring from NSString?
  • 时间:2009-10-23 09:31:14
  •  标签:

我有像@"abc xyz这样的空间红外线。 http://www.example.com aa bbb ccc"

如何从中抽取“@”的次量?

问题回答

我知道这是一个很晚的答复,但你可以拿到“http://www.abc.com”这一代号,其代码如下:

[@"abc xyz http://www.abc.com aaa bbb ccc" substringWithRange:NSMakeRange(8, 18)]

当然,你仍可为此使用<代码>NSString

为此:

       [yourString substringToIndex:<#(NSUInteger)#>];
//or
      [yourString substringFromIndex:<#(NSUInteger)#>];
//or        
      [yourString substringWithRange:<#(NSRange)#>];

If all of your substrings are separated by spaces, you can try to get an array of substrings using [myString componentsSeparatedByString:@" "]. Then you can check result of [NSUrl URLWithString:yourSubstring]. It will return nil if the substring isn t a correct link.

Here is my version of the script... Hopefully it s clean and easy to implement. It does a substr of the characters based on limits... Mine is used for a textarea, but can obviously be adapted to textfields :)

 -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
 {

      int maxLength = 100;
      int currentLength = [self.messageField.text length];

      if( currentLength > maxLength )
      {

           NSString *newMessageText = [self.messageField.text substringWithRange:NSMakeRange(0, maxLength)];

           [self.messageField setText:newMessageText];

           return NO;

     }
     else
     {

           return YES;

     }

 }

这也可以试图解决这一问题:

NSArray  *data = [@"abc xyz http://www.abc.com aaa bbb ccc" componentsSeparatedByString:@" "];

for(NSString* str in data)
{
    if([NSURLConnection canHandleRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]])
        NSLog(@"%@",[[NSString alloc ] initWithFormat:@"Found a URL: %@",str]);
}

希望!

如果你的投入说明有简单的保证(例如,舱面的标注总是由空间特性划定的保证),那么就将空间特性分开,并测试每个要素:@”http://

NSString *input = @"abc xyz http://www.example.com aaa bbb ccc";

NSArray *parts = [input componentsSeparatedByString:@" "];
for (NSString *part in parts) {
    if ([part hasPrefix:@"http://"]) {
        // Found it!
    }
}

可以根据申请需求优化这一方法;例如,一旦发现该元素或使用Kit的过滤器,选择短路,只接收从预设装置开始的内容。 理想的解决办法将取决于所展示的投入的性质以及你为实现这一目标而重新尝试的。





相关问题
热门标签