如何比较字符串?

时间:2015-09-18 08:21:16

标签: objective-c

在我的项目中,我在另一个视图控制器的列表中添加了许多单词,我需要检查列表中的单词是否相同。 这是代码,请帮助我需要做的事情

-(IBAction)save:(id)sender{
    if ([listName.text isEqualToString:@""]) {
        UIAlertView *error = [[UIAlertView alloc] initWithTitle:nil message:@"Please enter List Name." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [error show];
    } else if (self.newlist) {
        if (listName.text.length > 0  ) {
            [[UIApplication sharedApplication] cancelAllLocalNotifications];
            NSDate *currDate = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString *dateString =  [dateFormatter stringFromDate:currDate];

            if (notification.on ) {
                NSString *dateStr = [[NSString alloc] initWithFormat:@"%@ %@",dateString, time.text ];

                [self saveList:dateStr:dateString];
                [self saveListImages];
                [self getlistdata];
            }else {
                [self saveList:@"2000-01-01 00:00":dateString];
            }
        }else{
            [listName becomeFirstResponder];
        }
    }
}

2 个答案:

答案 0 :(得分:0)

在可变数组中添加字符串,并在比较器下方调用以检查重复项。下面的代码可以确保不区分大小写的检查,因此不允许TESTtest进入同一个数组。

NSMutableArray *myArray = [NSMutableArray arrayWithArray:@[@"TEST", @"Data"]];

NSString *testString = @"Test";

NSInteger index = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return (BOOL)([obj caseInsensitiveCompare:testString] == NSOrderedSame);
}];

if (index != NSNotFound) {
    NSLog(@"String already entered. Throw error");
} else {
    [myArray addObject:testString];
}

答案 1 :(得分:0)

NSOrderedSet *uniqueWordSet = [NSOrderedSet orderedSetWithArray:arrayWithDuplicates];
NSArray *unwiqueWordList = uniqueWordSet.array; // If you need it as array