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?
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.
Use -hasPrefix:
and -hasSuffix:
:
NSString *s = @"foobar";
NSLog(@"%d %dn", [s hasPrefix:@"foo"], [s hasSuffix:@"bar"]);
// Output: "1 1"
-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.
Python has string.startswith()
and string.endswith()
functions which are pretty useful.
What NSString methods can I use to have the same function?
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.
Use -hasPrefix:
and -hasSuffix:
:
NSString *s = @"foobar";
NSLog(@"%d %dn", [s hasPrefix:@"foo"], [s hasSuffix:@"bar"]);
// Output: "1 1"
-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.