我有一个字符串数组,如:Array = P123,P234,P543,P678
我有像P12300这样的字符串.(这可以是数组内的相同字符串,也可以没有trailling零).
我正在使用containsObject
if(Array containsObject: P123) ==> TRUE
if(Array containsObject: P23400) ==> FALSE
if(Array containsObject: P1230) ==> FALSE
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法来比较字符串,以便所有情况的上述情况都是真的?
目前我正在使用containsObject,并且我没有得到期望的结果,因为条件仅对于完全相同的字符串才是真的.
请让我知道好方法..
目标c
你可以用NSPredicate它.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", @"P123"];
NSArray *filterArray = [yourArray filteredArrayUsingPredicate: predicate];
if (filterArray.count > 0) {
print("Contains")
}
else {
print("Not")
}
Run Code Online (Sandbox Code Playgroud)
迅速
是的,您可以这样检查,您只需要使用contains(where:)它.
if yourArray.contains(where: { $0.hasPrefix("P123") }) {
print("Contains")
}
else {
print("Not")
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果要忽略尾随零,可以在将其与数组进行比较之前截断尾随零.
NSString *str = @"P12300";
NSRange range = [str rangeOfString:@"0*$" options:NSRegularExpressionSearch];
str = [str stringByReplacingCharactersInRange:range withString:@""];
NSLog(@"%@", str); //P123
//Now use this str to check its inside the array or not
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", str];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
320 次 |
| 最近记录: |