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

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


Use -hasPrefix: and -hasSuffix::

NSString *s = @"foobar";
NSLog(@"%d %d\n", [s hasPrefix:@"foo"], [s hasSuffix:@"bar"]);
// Output: "1 1"

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.

-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.

Need Your Help

iphone: get User Defined variable in Target's setting by code?

iphone xcode target xcconfig

My project have multi-targets. Each target has its own Class file for setting stuff. I want to store that Class name in a target setting (Info.plist or Target's Building setting). So that I can def...

Multiple javascript/css files: best practices?

php javascript jquery html css

I have about 7 Javascript files now (thanks to various jQuery plugins) and 4-5 CSS files. I'm curious as to what's the best practice for dealing with these including where in the document they sho...