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?

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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

8 Comments

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').
@kmcgrady, this method will return YES for the example you gave (finding boo in 'aaabooaaa'). Are you saying that it won't do that?
Apologies, didn't think it would work but I just tested it and it does. Much more compact than my solution too. Thanks!
@kmcgrady, do you see either of theses methods in your Xcode documentation? I only found them with a search on SO.
@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.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.