ios 如何在 Objective-C 中测试字符串是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/899209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I test if a string is empty in Objective-C?
提问by Jamey McElveen
How do I test if an NSString
is empty in Objective-C?
如何NSString
在 Objective-C 中测试 an是否为空?
回答by Marc Charbonneau
You can check if [string length] == 0
. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length
on nil will also return 0.
您可以检查是否[string length] == 0
. 这将检查它是否是一个有效但为空的字符串 (@"") 以及它是否为 nil,因为调用length
nil 也会返回 0。
回答by Matt G
Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty
, which he shared on his blog:
马克的回答是正确的。但我将借此机会包括一个指向 Wil Shipley 的generalized 的指针isEmpty
,他在他的博客上分享了这一点:
static inline BOOL IsEmpty(id thing) {
return thing == nil
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}
回答by SEQOY Development Team
The first approach is valid, but doesn't work if your string has blank spaces (@" "
). So you must clear this white spaces before testing it.
第一种方法是有效的,但如果您的字符串有空格 ( @" "
)则不起作用。因此,您必须在测试之前清除这些空白区域。
This code clear all the blank spaces on both sides of the string:
此代码清除字符串两侧的所有空格:
[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
One good idea is create one macro, so you don't have to type this monster line:
一个好主意是创建一个宏,这样您就不必键入以下怪物行:
#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]
Now you can use:
现在您可以使用:
NSString *emptyString = @" ";
if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");
回答by Rob
One of the best solution I ever seen (better than Matt G's one) is this improved inline function I picked up on some Git Hub repo (Wil Shipley's one, but I can't find the link) :
我见过的最好的解决方案之一(比 Matt G 的更好)是我在一些 Git Hub 存储库(Wil Shipley 的一个,但我找不到链接)上找到的改进的内联函数:
// Check if the "thing" passed is empty
static inline BOOL isEmpty(id thing) {
return thing == nil
|| [thing isKindOfClass:[NSNull class]]
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}
回答by Rob
You should better use this category:
你最好使用这个类别:
@implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
@end
回答by user4951
I put this:
我把这个:
@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
return !(self == nil
|| [self isKindOfClass:[NSNull class]]
|| ([self respondsToSelector:@selector(length)]
&& [(NSData *)self length] == 0)
|| ([self respondsToSelector:@selector(count)]
&& [(NSArray *)self count] == 0));
};
@end
The problem is that if self is nil, this function is never called. It'll return false, which is desired.
问题是如果 self 为零,则永远不会调用此函数。它会返回 false,这是我们想要的。
回答by chown
Another option is to check if it is equal to @""
with isEqualToString:
like so:
另一种选择是,以检查它是否等于@""
与isEqualToString:
像这样:
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}
回答by Mani
Just pass your string to following method:
只需将您的字符串传递给以下方法:
+(BOOL)isEmpty:(NSString *)str
{
if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
return YES;
}
return NO;
}
回答by Samir Jwarchan
Just use one of the if
else
conditions as shown below:
只需使用if
else
如下所示的条件之一:
Method 1:
方法一:
if ([yourString isEqualToString:@""]) {
// yourString is empty.
} else {
// yourString has some text on it.
}
Method 2:
方法二:
if ([yourString length] == 0) {
// Empty yourString
} else {
// yourString is not empty
}
回答by Suragch
Swift Version
迅捷版
Even though this is an Objective C question, I needed to use NSString
in Swift so I will also include an answer here.
尽管这是一个 Objective C 问题,但我需要NSString
在 Swift 中使用,所以我也会在这里提供一个答案。
let myNSString: NSString = ""
if myNSString.length == 0 {
print("String is empty.")
}
Or if NSString
is an Optional:
或者如果NSString
是可选的:
var myOptionalNSString: NSString? = nil
if myOptionalNSString == nil || myOptionalNSString!.length == 0 {
print("String is empty.")
}
// or alternatively...
if let myString = myOptionalNSString {
if myString.length != 0 {
print("String is not empty.")
}
}
The normal Swift String
version is
正常的 SwiftString
版本是
let myString: String = ""
if myString.isEmpty {
print("String is empty.")
}
See also: Check empty string in Swift?
另请参阅:在 Swift 中检查空字符串?