views:

76

answers:

2

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?

+1  A: 

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.

Carl Norum
Looks like I was trying to make things needlessly complicated. Many thanks for such an elegant solution.
Garry
A: 

btw, no need for pointer type when using NSRange, because it is struct.

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

range = [sourceString rangeOfString:queryString];
xvga