Objective-C: Best way to extract substring from NSString?

喜你入骨 提交于 2019-11-27 03:02:21

问题


I have a space-separated string like @"abc xyz http://www.example.com aaa bbb ccc".

How can I extract the substring @"http://www.example.com" from it?


回答1:


I know this is a very late reply, but you can get the substring "http://www.abc.com" with the following code:

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

Of course, you can still use an NSString for that.




回答2:


Try this:

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



回答3:


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.




回答4:


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;

     }

 }



回答5:


This can also try to resolve this issue:

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

Hope it helps!




回答6:


I find PHP's substr() really convenient. Check out my NSString category if you're looking to be able to do something like this:

substr(@"abc xyz http://www.example.com aaa bbb ccc", 8,-12)

or

substr(@"abc xyz http://www.example.com aaa bbb ccc", 8, 18)

Both will give you the result of http://www.example.com

Here's a copy of the relevant piece of code:

__attribute__((overloadable))
NSString *substr(NSString *str, int start)
{
    return substr(str, start, 0);
}

__attribute__((overloadable))
NSString *substr(NSString *str, int start, int length)
{
    NSInteger str_len = str.length;
    if (!str_len) return @"";
    if (str_len < length) return str;
    if (start < 0 && length == 0)
    {
        return [str substringFromIndex:str_len+start];
    }
    if (start == 0 && length > 0)
    {
        return [str substringToIndex:length];
    }
    if (start < 0 && length > 0)
    {
        return [[str substringFromIndex:str_len+start] substringToIndex:length];
    }
    if (start > 0 && length > 0)
    {
        return [[str substringFromIndex:start] substringToIndex:length];
    }
    if (start > 0 && length == 0)
    {
        return [str substringFromIndex:start];
    }
    if (length < 0)
    {
        NSString *tmp_str;
        if (start < 0)
        {
            tmp_str = [str substringFromIndex:str_len+start];
        }
        else
        {
            tmp_str = [str substringFromIndex:start];
        }
        NSInteger tmp_str_len = tmp_str.length;
        if (tmp_str_len + length <= 0) return @"";
        return [tmp_str substringToIndex:tmp_str_len+length];
    }

    return str;
}



回答7:


A possible solution might be using regular expressions. Check out RegexKit.




回答8:


If your input string has simple guarantees (for example the guarantee that tokens in the string are always delineated by a space character) then split on the space character and test each element for @"http://" as a prefix.

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!
    }
}

This can be optimized this based on the application's needs; for example, choose to short-circuit the loop once the element is found or use filters in BlocksKit to get only elements that begin with the prefix. An ideal solution will depend on the nature of the input string and what you're trying to accomplish with it.



来源:https://stackoverflow.com/questions/1612337/objective-c-best-way-to-extract-substring-from-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!