Check if an NSString is just made out of spaces

前端 未结 10 2218
夕颜
夕颜 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:09

    Try stripping it of spaces and comparing it to @"":

    NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    BOOL wereOnlySpaces = [probablyEmpty isEqualToString:@""];
    
    0 讨论(0)
  • 2020-12-14 06:09

    Here's the Swift version code for the same,

    var str = "Hello World" 
    if count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0 {
         // String is empty or contains only white spaces
    }
    else {
        // String is not empty and contains other characters
    }
    

    Or you can write a simple String extension like below and use the same code with better readability at multiple places.

    extension String {
        func isEmptyOrContainsOnlySpaces() -> Bool {
            return count(self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0
        }
    }
    

    and just call it using any string like this,

    var str1 = "   "
    if str.isEmptyOrContainsOnlySpaces() {
        // custom code e.g Show an alert
    }
    
    0 讨论(0)
  • 2020-12-14 06:13

    Trim space and check for number of characters remaining. Take a look at this post here

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

    I'm really surprised that I am the first who suggests Regular Expression

    NSString *string = @"         ";
    NSString *pattern = @"^\\s*$";
    NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    NSArray *matches = [expression matchesInString:string options:0 range:NSMakeRange(0, string.length)];
    BOOL isOnlyWhitespace = matches.count;
    

    Or in Swift:

    let string = "         "
    let pattern = "^\\s*$"
    let expression = try! NSRegularExpression(pattern:pattern)
    let matches = expression.matches(in: string, range: NSRange(string.startIndex..., in: string))
    let isOnlyWhitespace = !matches.isEmpty
    

    Alternatively

    let string = "         "
    let isOnlyWhitespace = string.range(of: "^\\s*$", options: .regularExpression) != nil
    
    0 讨论(0)
  • 2020-12-14 06:14

    Here is an easily reusable category on NSString based on @Alexander Akers' answer, but that also returns YES if the string contains "new lines"...

    @interface NSString (WhiteSpaceDetect)
    @property (readonly) BOOL isOnlyWhitespace;
    @end
    @implementation NSString (WhiteSpaceDetect)
    - (BOOL) isOnlyWhitespace { 
      return ![self stringByTrimmingCharactersInSet:
              [NSCharacterSet whitespaceAndNewlineCharacterSet]].length;
    }
    @end
    

    and for those of you untrusting souls out there..

    #define WHITE_TEST(x) for (id z in x) printf("\"%s\" : %s\n",[z UTF8String], [z isOnlyWhitespace] ? "YES" :"NO")
    
    WHITE_TEST(({ @[
    
        @"Applebottom",
        @"jeans\n",
        @"\n",
        @""
        "",
        @"   \
        \
        ",
        @"   "
    ];}));
    

    "Applebottom" : NO
    "jeans
    " : NO
    "
    " : YES
    "" : YES
    "   " : YES
    "   " : YES
    
    0 讨论(0)
  • 2020-12-14 06:29

    Here is a simple Swift solution:

    //Check if string contains only empty spaces and new line characters
    static func isStringEmpty(#text: String) -> Bool {
        let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
        let newText = text.stringByTrimmingCharactersInSet(characterSet)
        return newText.isEmpty
    }
    
    0 讨论(0)
提交回复
热议问题