Ketan Shinde
Ketan Shinde

Reputation: 1847

range of substring in a string

I have an array containing object let say { my saxophone, take, everywhere}. Secondly i have a NSString: 'take my saxophone everywhere' then how can I able to match object of array with string and get index from NSString. I need index of substring from NSString by comparing with objects of array. So that i can sort the array correctly. So far I have done

NSRange range = [feedBackAnswer rangeOfString:@"everywhere"];
        if ( range.length > 0 ) 
        {
            NSLog(@"range.location..%d",range.location);
        } 
        else 
        {
            NSLog(@"...%d",-1);
        }

But I could not find the index of substring.

Upvotes: 1

Views: 195

Answers (3)

Thukaram
Thukaram

Reputation: 1083

Try this code

NSMutableArray *array1 = [NSMutableArray arrayWithObjects:@"my",@"saxophone",@"take",@"everywhere", nil];

NSString *str1 = @"take my saxophone everywhere";

NSArray *array = [str1 componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@" objects : %@",array);

for (int i=0; i<[array count]; i++) {
    for (int j=0; j<[array count]; j++) {
    if ([[array objectAtIndex:i] isEqualToString:[array1 objectAtIndex:j]]) {
        NSLog(@"String :%@ no : %d ",[array objectAtIndex:i],j);
        }
    }
}

Upvotes: 0

Satyam
Satyam

Reputation: 1682

Range of sub string in a string is ...

   0: U

   1: n

   2: i

   3: v

   4: e

   5: r

   6: s

   7: i

   8: t

   9: y

Upvotes: 0

Rams
Rams

Reputation: 1751

    NSMutableArray * data=[[NSMutableArray alloc]initWithObjects:@"my saxophone",@"take",@"everwhere", nil];
        NSString * mat=@"take my saxophone everywhere";
        for (int i=0; i<[data count]; i++) {
            NSRange range = [mat rangeOfString:[data objectAtIndex:i]];
            if (range.length > 0)
                NSLog(@"Range is: %@", NSStringFromRange(range));
            else
                NSLog(@"Failed"); 
        }

[data release];

& check the spelling in array (everwhere)

Upvotes: 1

Related Questions