Question

I am using the following query to check if the strings within a NSArray contain a certain word.

I am struggling to then break it down to display only the string that has the rangeOfString word.

As you can see it currently displays all the results if the NSArray contains the word. How would I single it down further to display only the specific string that contains the "BOLDME" ?

// change this line only for the concatenation
        NSString * resultConditions = [legislationArray componentsJoinedByString:@"\n"];

        NSString *word = @"BOLDME";
        //if string contains
        if ([resultConditions rangeOfString:word].location != NSNotFound) {

            cell.dynamicTextView.text = resultConditions;

        }
Was it helpful?

Solution

Not only will this get you directly to each instance within the array that contains the text you're searching for, but it will also perform significantly better than the code in the question.

for (NSString *testWord in legislationArray) {
    if ([testWord rangeOfString:@"BOLDME"].location != NSNotFound) {
        // testWord contains "BOLDME"
        cell.dynamicTextView.text = 
            [cell.dynamicTextView.text stringByAppendingString:testWord];
    }
}

As written, this will append the found string to whatever text is already in the text view. It may be that you only want one word in the text view. If this is the case, then you should break; as soon as you find the first one.

OTHER TIPS

You can iterate over NSArray and check each string if it contains specific word:

for(NSString *value in array) {
    if([value rangeOfString:word] != NSNotFound) { 
        /* we have found that string*/ 
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top