Objective-C (cocoa) equivalent to python's endswith/beginswith

Question:

Python has string.startswith() and string.endswith() functions which are pretty useful.
What NSString methods can I use to have the same function?

Asked By: prosseek

||

Answers:

You want the hasPrefix and hasSuffix messages.

I tend to also use the compare:options: message pretty regularly to achieve the same but with case-insensitive comparison.

Answered By: Mac

Use -hasPrefix: and -hasSuffix::

NSString *s = @"foobar";
NSLog(@"%d %dn", [s hasPrefix:@"foo"], [s hasSuffix:@"bar"]);
// Output: "1 1"
Answered By: Adam Rosenfield

-hasPrefix() and -hasSuffix() return YES or NO depending on whether the receiver begins or ends with the given substring. If that’s what startswith() and endswith() do, then that’s your answer.

Answered By: Caleb
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.