【问题标题】:How to check whether a string contains white spaces如何检查字符串是否包含空格
【发布时间】:2011-12-05 09:12:55
【问题描述】:

如何检查字符串中字符之间是否包含空格?

【问题讨论】:

标签: iphone ios nsstring whitespace


【解决方案1】:

使用rangeOfCharactersFromSet:

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

注意:这也会在字符串的开头或结尾找到空格。如果您不想先修剪字符串...

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

【讨论】:

    【解决方案2】:

    您也可以按照以下步骤操作:

    NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "];
    

    如果您的字符串中有任何空格,那么它将分隔这些空格并将不同的组件存储在数组中。现在您需要计算数组的数量。如果 count 大于 1,则表示有两个分量,即存在空白。

    if([componentsSeparatedByWhiteSpace count] > 1){
        NSLog(@"Found whitespace");
    }
    

    【讨论】:

    • 请注意,这非常慢。 testString 越长,与我使用的 rangeOfCharacterFromSet: 方法相比,它变得越慢。因为今天早上比较无聊,对比了两种方法的性能,写了blog post
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2012-07-14
    • 2021-08-17
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多