Check if an NSString is just made out of spaces

前端 未结 10 2219
夕颜
夕颜 2020-12-14 05:35

I want to check if a particular string is just made up of spaces. It could be any number of spaces, including zero. What is the best way to determine that?

相关标签:
10条回答
  • 2020-12-14 06:30

    It's significantly faster to check for the range of non-whitespace characters instead of trimming the entire string.

    NSCharacterSet *inverted = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
    NSRange range = [string rangeOfCharacterFromSet:inverted];
    BOOL empty = (range.location == NSNotFound);
    

    Note that "filled" is probably the most common case with a mix of spaces and text.

    testSpeedOfSearchFilled - 0.012 sec
    testSpeedOfTrimFilled - 0.475 sec
    testSpeedOfSearchEmpty - 1.794 sec
    testSpeedOfTrimEmpty - 3.032 sec
    

    Tests run on my iPhone 6+. Code here. Paste into any XCTestCase subclass.

    0 讨论(0)
  • 2020-12-14 06:30

    Try this:

    [mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    

    or

    [mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    0 讨论(0)
  • 2020-12-14 06:31

    Have to use this code for Swift 3:

    func isEmptyOrContainsOnlySpaces() -> Bool {
    
        return self.trimmingCharacters(in: .whitespaces).characters.count == 0
    }
    
    0 讨论(0)
  • 2020-12-14 06:34
    NSString *str = @"         ";
    NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
    if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
    {
        // String contains only whitespace.
    }
    
    0 讨论(0)
提交回复
热议问题