IOS : containsObject Check for String

i have Array of String like: Array = P123, P234, P543, P678

and i have string like P12300.(this can be same string inside array or without trailling zeros).

i was using containsObject

if(Array containsObject: P123)    ==> TRUE
if(Array containsObject: P23400)  ==> FALSE
if(Array containsObject: P1230)    ==> FALSE

is there any better way to compare string so that above ALL case's will be true?

at present i am using containsObject, and i am not getting desired result as condition will be only true for exact same string.

Please let me know good way..


Objective c

You can use NSPredicate for that.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[c] %@", @"P123"];
NSArray *filterArray = [yourArray filteredArrayUsingPredicate: predicate];
if (filterArray.count > 0) {
    print("Contains")
}
else {
    print("Not")
}

Swift

Yes , You can check like that, you need to simply use contains(where:) for that.

if yourArray.contains(where: { $0.hasPrefix("P123") }) {
    print("Contains")
}
else {
    print("Not")
}

Edit: If you want to ignore the trailing zeros you can truncate the trailing zero before comparing it with array.

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];

You may want to use [string1 isEqualToString:string2]

In that case it will evaluate to true only if strings are equal.

You may also use containString method. You may find this link helpfull.


NSPredicate is nice, another way is using containsString: method like

//assumes all objects in the array are NSStrings
- (NSArray *)array:(NSArray *)array containsSubstring:(NSString *)substring {
    NSMutableArray *newArray = [[NSMutableArray alloc] init];
    for (NSString *string in array) {
        if([string containsString:substring]) {
            [newArray addObject:string];
        }
    }
    return newArray;
}

now you can call it like

NSArray *stringArray = @[@"P12300", @"P23400", @"P5430", @"P678"];
NSArray *subArray = [self array:stringArray containsSubstring:@"P23"];
NSLog(@"%@", subArray);

Swift 3:

in Swift it's super easy using filter

let array: [String] = ["P12300", "P23400", "P5430", "P678"]
let newArray = array.filter {
    $0.contains("P123")
}
print(newArray)
链接地址: http://www.djcxy.com/p/74012.html

上一篇: Javascript中有RegExp.escape函数吗?

下一篇: IOS:containsObject检查字符串