45

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?

awhie29urh2
  • 15,547
  • 2
  • 19
  • 20
ThyPhuong
  • 483
  • 1
  • 4
  • 5

8 Answers8

59

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.

Justin
  • 2,122
  • 3
  • 27
  • 47
  • It seems not to work when my string is shorter than the range, what can I do then? – powtac Dec 06 '12 at 00:01
  • 2
    You simply give it a different range. It may be best to check the length `[@"Some string" length]` and add that number to the first to find the second. – Justin Dec 06 '12 at 20:26
30

Try this:

       [yourString substringToIndex:<#(NSUInteger)#>];
//or
      [yourString substringFromIndex:<#(NSUInteger)#>];
//or        
      [yourString substringWithRange:<#(NSRange)#>];
Pach
  • 861
  • 11
  • 18
12

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.

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
Morion
  • 10,495
  • 1
  • 24
  • 33
  • Maybe you misunderstood me or maybe I misunderstood you but http://www.abc.com is just an example. What I mean is how to get a substring have format of an url link from the NSString. Waiting for your reply – ThyPhuong Oct 24 '09 at 06:10
  • Hmm... NSArray* subStrings = [yourString componentsSeparatedByString:@" "]; for(NSString* subString in subStrings){ if([NSUrl URLWithString: subString]){ NSLog(@"This substring is an URL: %@", subString); } } – Morion Oct 24 '09 at 12:05
  • If your substrings are separated by @" ", you will see in console all substrings, that are correct URLs. – Morion Oct 24 '09 at 12:07
5

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;

     }

 }
rckehoe
  • 1,198
  • 15
  • 16
2

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!

2

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;
}
mmackh
  • 3,550
  • 3
  • 35
  • 51
0

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

Jonathan Sterling
  • 18,320
  • 12
  • 67
  • 79
  • 2
    Regexp is almost always the wrong solution. Especially matching URLs is _very_ hard as the correct regexp is really long. Matching e-mail addresses for example is hard: http://www.regular-expressions.info/email.html – Georg Schölly Oct 25 '09 at 15:04
  • "Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems." http://regex.info/blog/2006-09-15/247 – Pierre Houston Jul 10 '13 at 21:41
0

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.

awhie29urh2
  • 15,547
  • 2
  • 19
  • 20