How to test a string for text

407 views Asked by At

I would like to test a string to see if anywhere it contains the text "hello". I would like the test to not take into account capitalization. How can I test this string?

5

There are 5 answers

0
Jhaliya - Praveen Sharma On BEST ANSWER

Use the below code as reference to find check for a substring into a string.

    NSString* string = @"How to test a string for text" ;
    NSString* substring  = @"string for" ;

    NSRange textRange;
    textRange =[string rangeOfString:substring  options:NSCaseInsensitiveSearch];

    if(textRange.location != NSNotFound)
    {

    //Does contain the substring
    }
0
AudioBubble On
1
James On

I am assuming all words are separated by a space, and that there is no punctuation. If there is punctuation.

NSArray *dataArray = [inputString componentsSeparatedByString:@" "];

for(int i=0; i<[dataArray count]){
 if([[dataArray objectAtIndex:i] isEqualToString:@"hello"]){
    NSLog(@"hello has been found!!!");
 } 
}

I haven't tested this but it should work in theory.

Check out the docs for ways to remove punctuation and make the string all lower case. This should be pretty straight-forward.

6
sciritai On

Other solutions here are good but you should really use a regex,

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(hello)*$"
                                                                   options:NSRegularExpressionCaseInsensitive
                                                                     error:&error];

Docs are here: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

0
Jano On
NSRange range = [string rangeOfString:@"hello" options:NSCaseInsensitiveSearch];
BOOL notFound = range.location==NSNotFound;