ThyPhuong
ThyPhuong

Reputation: 483

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

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?

Upvotes: 45

Views: 70438

Answers (8)

mmackh
mmackh

Reputation: 3630

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

Upvotes: 2

candieduniverse
candieduniverse

Reputation: 16186

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.

Upvotes: 0

rckehoe
rckehoe

Reputation: 1198

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;

     }

 }

Upvotes: 5

Pach
Pach

Reputation: 861

Try this:

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

Upvotes: 30

user1873574
user1873574

Reputation: 93

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!

Upvotes: 2

Morion
Morion

Reputation: 10860

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.

Upvotes: 12

Justin
Justin

Reputation: 2142

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.

Upvotes: 59

Jonathan Sterling
Jonathan Sterling

Reputation: 18385

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

Upvotes: 0

Related Questions