Sunday, May 19, 2013

NSString rangeOfString example ios


[NSString rangeOfString]

Finds and returns the range of the first occurrence of a given string within the receiver.
- (NSRange)rangeOfString:(NSString *)aString
Parameters
aString
The string to search for. This value must not be nil.

Important: Raises an NSInvalidArgumentException if aString is nil.
Return Value of [NSString rangeOfString]
An NSRange structure giving the location and length in the receiver of the first occurrence of aString. Returns {NSNotFound, 0} if aString is not found or is empty (@"").
Discussion of [NSString rangeOfString]
Invokes rangeOfString:options: with no options.
This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.
Example of [NSString rangeOfString]
if ([@"abc" rangeOfString:@"d"].location == NSNotFound){
  //Do something
Example of [NSString rangeOfString]
NSRange range = [name rangeOfString: @"Arnold"];
NSUInteger start = range.location;
NSUInteger end = start + range.length;
Example of [NSString rangeOfString]
NSString *string = @"{Hello} ({World}) ({How}) ({Are}) ({You})";
    NSMutableString *result = [[NSMutableString alloc] init];

    NSArray *tempArray = [[string componentsSeparatedByString:@" "] mutableCopy];

    for (int i=0; i < [tempArray count]; i++)
    {
        NSString *tempStr = [tempArray objectAtIndex:i];
        NSRange startRange = [tempStr rangeOfString:@"{" options:NSCaseInsensitiveSearch];
        if (startRange.location != NSNotFound)
        {
            // Determine "}" location according to "{" location
            NSRange endRange;

            endRange.location = startRange.length + startRange.location;
            endRange.length   = [tempStr length] - endRange.location;
            endRange = [tempStr rangeOfString:@"}" options:NSCaseInsensitiveSearch range:endRange];

            if (endRange.location != NSNotFound)
            {
                // bracets found: retrieve string between them
                startRange.location += startRange.length;
                startRange.length = endRange.location - startRange.location;

                //result = [tempStr substringWithRange:startRange];
                [result appendString:[NSString stringWithFormat:@"%@ ",[tempStr substringWithRange:startRange]]];
                NSLog(@"%@ ",result);

            }
        }
    }