-1

我在得到字符串的响应中调用 webservice。当我在 NSLog 中打印字符串时,它返回空字符串,当我检查长度时,它返回 1。

所以我的问题是我如何检查字符串是否为空。

#define CHECK_NA_STRING(str) (str == (id)[NSNull null] || [str length] == 0)?@"N/A":str

NSLog(@"%@",CHECK_NA_STRING([dict objectForKey:@"ADDRESS_A"]));  // nothing empty string
NSLog(@"%d",[CHECK_NA_STRING([dict objectForKey:@"ADDRESS_A"]) length]); // return 1

那么如何检查该字符串是否为空?谢谢。

4

2 回答 2

0

如果字符串包含二进制零(空字符),则不认为该字符串为空。例如,试试这个代码:

#define CHECK_NA_STRING(str) (str == (id)[NSNull null] || [str length] == 0)?@"N/A":str
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"\0" forKey:@"ADDRESS_A"];
NSLog(@"%@",CHECK_NA_STRING([dict objectForKey:@"ADDRESS_A"]));  // nothing empty string
NSLog(@"%d",[CHECK_NA_STRING([dict objectForKey:@"ADDRESS_A"]) length]); // return 1

第一个 NSLOG 不会打印任何内容,但第二个将打印“1”。实际上,字符串只有一个字符长;它只会弄乱你的 NSLOG。

您可能想要测试一些有效的响应范围或一些无效的范围。也许,您可以使用正则表达式。

于 2013-10-06T06:01:52.967 回答
0

所以字符串只是一个空格?那么它的长度仍然为 1。

尝试:

NSString* string = ...;

if([string isKindOfClass:[NSString class]])
{
    NSCharacterSet* invertedWhitespaceSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];

    const NSRange nonEmptyCharacterRange = [string rangeOfCharacterFromSet:invertedWhitespaceSet options:NSCaseInsensitiveSearch];  

    if(nonEmptyCharacterRange.location == NSNotFound)
    {
        //  Empty invalid string    
    }
    else
    {
        //  Non-empty valid string
    }
}
于 2013-10-06T08:45:21.130 回答