How to check whether a string contains white spaces

后端 未结 2 1407
北海茫月
北海茫月 2021-02-05 05:49

How to check whether a string contains whitespaces in between characters?

2条回答
  •  庸人自扰
    2021-02-05 06:34

    use rangeOfCharactersFromSet:

    NSString *foo = @"HALLO WELT";
    NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
    if (whiteSpaceRange.location != NSNotFound) {
        NSLog(@"Found whitespace");
    }
    

    note: this will also find whitespace at the beginning or end of the string. If you don't want this trim the string first...

    NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
    

提交回复
热议问题