Objective-C (Cocoa) 对应 Python 的 endswith/beginswith 方法
Python有两个很实用的函数,分别是string.startswith()
和string.endswith()
。这两个函数可以用来检查一个字符串是不是以某个特定的内容开始或者结束。那么在NSString中,我可以用哪些方法来实现同样的功能呢?
3 个回答
5
-hasPrefix() 和 -hasSuffix() 这两个方法会根据接收的字符串是否以给定的子字符串开头或结尾来返回YES(是)或NO(不是)。如果这正是startswith() 和 endswith() 的功能,那么这就是你的答案。
8
你想要使用 hasPrefix
和 hasSuffix
这两个方法。
我通常还会用到 compare:options:
这个方法,来做类似的事情,不过它可以忽略大小写的差异。
64
使用 -hasPrefix:
和 -hasSuffix:
:
NSString *s = @"foobar";
NSLog(@"%d %d\n", [s hasPrefix:@"foo"], [s hasSuffix:@"bar"]);
// Output: "1 1"