سؤال

I am working on an iOS application where a user is required to enter their first and last name into a UITextField. Now, I want my UITextField to be able to check to see that the user has entered:

(1) two names and (2) each name is a minimum of two characters.

My problem is that when I retrieve the name(s) from the text field, I am unable to distinguish between an empty NSString (i.e. " "), and an NSString that is composed of characters. Because of this, when I check to see what the length of the shortest word that has been entered is, the empty spaces are always counted as being valid strings, which I don't want. So in other words, if a user enters:

" larry bird "

I need the string count to be two, and the length of the shortest word to be 4 (thus passing both tests). So I need the leading, trailing whitespaces as well as the whitespaces in between to be removed, but keep the NSString objects that are valid to be distinct.

Here is the code that I have thus far:

NSString *name = [textField text];
        NSArray *trimmedArray = [name componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSMutableArray *trimmedNames = [NSMutableArray array];

        for (NSString *cleanString in trimmedArray) {

            NSString *trimmedString = [cleanString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            NSLog(@"The trimmed name is: %@", trimmedString);
            [trimmedNames addObject:trimmedString];
        }

        self.alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please Enter Full First and Last Name" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

        if(trimmedNames.count > 1) {

            NSNumber *lengthOfShortestWord = [trimmedNames valueForKeyPath:@"@min.length"];//here is where I am counting the characters in the smallest string entered the textfield

            if (lengthOfShortestWord.intValue > 1) {

                [textField resignFirstResponder];

            }

            else if (lengthOfShortestWord.intValue <= 1) {

                [self.alert show];

            }

        }

        else if (trimmedNames.count < 2) {

            [self.alert show];

        }

Does anyone see what it is that I am doing wrong?

هل كانت مفيدة؟

المحلول

Trim the white space from the initial string from the text field.

NSString *name = [[textField text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Now you don't need to trim each individual string.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top