如何检查 [request responseString] 是否等于其他字符串?
例如,我的 servlet 发送到我的 iPhone 应用程序的 [request responseString] 值是“myinfo”。在我的 iPhone 应用程序中,我制作了一个像这样的字符串:
NSString *str = @"myinfo";
然后我
if([responseString isEqualToString:str]){
NSLog(@"condition true");
}else{
NSLog(@"condition false");
}
在控制台中的 if else 总是显示“条件为假”。有什么问题吗? isEqualToString 不是检查字符串是否相等的 write 方法吗?提前致谢。
For example [request responseString]'s value sent by my servlet to my iphone application is "myinfo". In my iphone application, I made a string like this:
NSString *str = @"myinfo";
then i have if else
if([responseString isEqualToString:str]){
NSLog(@"condition true");
}else{
NSLog(@"condition false");
}
in console its always showing "condition false". Whats the problem? Isn't isEqualToString is write method to check if strings are equal or not? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
无论您多么认为您的两个字符串完全相等,它们都不是。相信我,如果
-isEqualToString:
对于两个相等的字符串没有返回YES
,有人会注意到在 20 多年里它已经成为 Cocoa API 的一部分。我怀疑您的两个字符串之一包含一些非打印字符。其中可能有换行符、空格或制表符。另一种可能性(我最近遇到的一种)是,对于某些字符集编码,您可以创建一个包含 nul 字符的
NSString
。如果是在最后,就不会出现。尝试记录两个字符串的长度,或者使用 UTF16 编码将它们转换为 NSData 对象并记录它们。Howwever much you think your two strings are completely equal, they are not. Believe me, if
-isEqualToString:
did not returnYES
for two equal strings, somebody would have noticed in the 20 odd years it has been part of the Cocoa API.I suspect that one of your two strings contains some non printing characters. You might have a line feed or a space or a tab in it. Another possibility (one that I came across recently) is that, for certain character set encodings, you can create an
NSString
with a nul character in it. If it's at the end, it won't show up. Try logging the lengths of the two strings, or converting them toNSData
objects using the UTF16 encoding and logging them.NSString
方法isEqualToString
是这里使用的正确方法。您可以通过向方法添加日志来进行完整性检查:请记住,
NSString
区分大小写,因此两个字符串必须完全相同。The
NSString
methodisEqualToString
is the correct thing to use here. You can do a sanity check by adding a log to your method:Remember that
NSString
s are Case Sensitive, so the two strings must appear exactly the same.既然你说你正在使用connectios,有时网络检索到的数据很奇怪,你应该首先将数据编码在字符串中,然后NSLog它以查看它是否有特殊字符。
然后您可以确定您的 [request responseString] 是否没有获得特殊字符。
Since you said you're using connectios, sometimes the data retrieved by web is weird, you should first encode the data in a string and then NSLog it to see if it has special characters.
Then you can make sure if your [request responseString] is not getting special chars.
ios中比较字符串的更好方法:
The better way to compare strings in ios: