Garry Pettet
Garry Pettet

Reputation: 8290

Specific Strings And NSScanner

I need to determine whether a string (sourceString) contains another string (queryString) and if it does, at what offset.

I'm guessing that NSScanner might do the trick but I don't fully understand the documentation.

Let's say sourceString = @"What's the weather in London today?"

If I set queryString to equal @"What's the weather", I'd like a method that would determine that, in this case, YES (sourceString does contain queryString) and the offset is 0 (i.e. at the start of sourceString).

Any suggestions?

Upvotes: 1

Views: 359

Answers (1)

Carl Norum
Carl Norum

Reputation: 224844

You don't need an NSScanner for that. Just use NSString's -rangeOfString: method. Something like:

NSString *sourceString = @"What's the weather in London today?";
NSString *queryString = @"What's the weather";
NSRange  range;

range = [sourceString rangeOfString:queryString];

After the last call, range will be {NSNotFound, 0} if queryString is not found. In this case, you'd get {0, 18}, though.

Check out the documentation.

Upvotes: 3

Related Questions