0

I'm trying to check if an NSString contains a substring. It's not working however as there is no space between the words in the string. e.g. I need to find out if 'hello' exists in this string:

@"test.hello"

NSString containsString does not find it. Any other solutions?

  • Unless Apple has done something weird with that interface `[@"test.hello" containsString:@"hello"]` should return `YES`. – Hot Licks Dec 02 '14 at 16:52
  • @HotLicks I thought so but it wasn't working for me. I've accepted the working answer. –  Dec 02 '14 at 17:07

2 Answers2

0

Update

This works but @rdelmar's answer is much more compact.

/////////////////////////////////////////////////////////////////////////////////////////////////

I discovered an answer elsewhere on SO. Basically I had to use NSRange and check via the following method:

[string rangeOfString:@"hello" options:NSCaseInsensitiveSearch].location != NSNotFound

I also had to split my string before doing the check. So in the example words are separated by a period. I called:

NSArray *myArray = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];

and the looped through that array of strings doing the rangeOfString search. I set a BOOL so that once my string 'hello' was found it stopped searching.

Community
  • 1
  • 1
0

iOS 8 has a new method, localizedCaseInsensitiveContainsString: also, in addition to containsString:.

NSString *testString = @"test.hello";
BOOL found = [testString localizedCaseInsensitiveContainsString:@"Hello"];
NSLog(@"%@", found ? @"Yes":@"No"); // prints Yes
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Good to know thanks! That was only part of the problem though. I had to separate the string into components as the containsString methods search for parts of a string, they won't pick out a string within a string (e.g. they can't get 'boo' from 'aaabooaaa'). –  Dec 02 '14 at 16:18
  • @kmcgrady, this method will return YES for the example you gave (finding boo in 'aaabooaaa'). Are you saying that it won't do that? – rdelmar Dec 02 '14 at 16:21
  • Apologies, didn't think it would work but I just tested it and it does. Much more compact than my solution too. Thanks! –  Dec 02 '14 at 16:36
  • @kmcgrady, do you see either of theses methods in your Xcode documentation? I only found them with a search on SO. – rdelmar Dec 02 '14 at 16:41
  • @rdelmar - They are not in the online documentation, and, worse, if you search for them you're apt to find some 3rd-party categories by the same name. – Hot Licks Dec 02 '14 at 16:53
  • The only reliable place I can find it is NSHipster: http://nshipster.com/ios8/ I can't see it in any documentation. –  Dec 02 '14 at 17:05
  • I found them in a "New for iOS 8" presentation from Apple, but no actual documentation. – Hot Licks Dec 02 '14 at 17:09
  • @HotLicks, I did find them in the NSString.h file where there is a comment explaining their use. – rdelmar Dec 02 '14 at 17:11