如何在Objective-C中测试NSString是否为空?
当前回答
if (string.length == 0) stringIsEmpty;
其他回答
你有两个方法来检查字符串是否为空:
让我们假设你的字符串名字是NSString *strIsEmpty。
方法1:
if(strIsEmpty.length==0)
{
//String is empty
}
else
{
//String is not empty
}
方法2:
if([strIsEmpty isEqualToString:@""])
{
//String is empty
}
else
{
//String is not empty
}
选择上述任何一种方法,了解字符串是否为空。
你可以检查[string length] == 0。这将检查它是否是一个有效的空字符串(@"")以及它是否为nil,因为在nil上调用length也将返回0。
- (BOOL)isEmpty:(NSString *)string{
if ((NSNull *) string == [NSNull null]) {
return YES;
}
if (string == nil) {
return YES;
}
if ([string length] == 0) {
return YES;
}
if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
return YES;
}
if([[string stringByStrippingWhitespace] isEqualToString:@""]){
return YES;
}
return NO;
}
我检查了一个空字符串使用以下代码:
//Check if we have any search terms in the search dictionary.
if( (strMyString.text==(id) [NSNull null] || [strMyString.text length]==0
|| strMyString.text isEqual:@"")) {
[AlertView showAlert:@"Please enter a valid string"];
}
第一种方法是有效的,但如果字符串中有空格(@" ")则无效。所以在测试之前必须清除这些空白。
这段代码清除了字符串两边的所有空格:
[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
一个好主意是创建一个宏,这样你就不必输入这一行怪物:
#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]
现在你可以使用:
NSString *emptyString = @" ";
if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务