Check if an NSString is just made out of spaces

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

提交回复
热议问题