Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
prosseek Avatar asked Mar 05 '11 05:03

prosseek


People also ask

What is Endswith function in Python?

The endswith() method returns True if a string ends with the specified suffix. If not, it returns False .

What is Endswith?

The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

How do I check if a string Endswith in Python?

The endswith() function returns True if a string ends with the specified suffix (case-sensitive), otherwise returns False. A tuple of string elements can also be passed to check for multiple options. If a string ends with any element of the tuple then the endswith() function returns True.


2 Answers

Use -hasPrefix: and -hasSuffix::

NSString *s = @"foobar";
NSLog(@"%d %d\n", [s hasPrefix:@"foo"], [s hasSuffix:@"bar"]);
// Output: "1 1"
like image 116
Adam Rosenfield Avatar answered Oct 27 '22 08:10

Adam Rosenfield


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.

like image 8
Mac Avatar answered Oct 27 '22 07:10

Mac