iOS:如何从缓冲区或字符串中删除空字符?
我正在尝试在 iOS 中与从网络流获取的字符串进行字符串比较。
读取流的代码是:
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable])
{
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
[self handleServerResponse: intCommand Response:output];
}else{
[self endComms];
}
}
另一端的服务器总是产生 1024 字节的响应,并将 chr(0) 放在数据的末尾以填充缓冲区。
当我进行字符串比较时:
if (strCut==@"B") {
//do something...
}
我总是得到负结果,大概是因为字符串包含响应和大量空字符。
我希望能够在将响应读入字符串时从缓冲区中删除空字符,但在 iOS 中我没有运气做到这一点。
帮助表示感谢!
谢谢。
戴夫
I am trying to do a string comparison in iOS with a string obtained from a network stream.
The code that reads the stream is:
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable])
{
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
[self handleServerResponse: intCommand Response:output];
}else{
[self endComms];
}
}
The server at the other end always produces responses of 1024 bytes, with chr(0) being placed at the end of the data to fill the buffer.
When I do a string comparison:
if (strCut==@"B") {
//do something...
}
I always get a negative result, presumably because the string contaings the response and lots of null characters.
I would like to be able to strip empty characters from the buffer when reading the response into the string, but I not having any luck in doing this in iOS.
Help appreciated!
Thanks.
Dave
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您对代码不起作用的原因做出了错误的假设。
更改
为:
供将来参考,切勿做出假设 - 使用调试器或其他工具来验证问题所在。您可能还想考虑阅读一本关于 Objective-C 的介绍性书籍。
You're making a bad assumption about why your code is not working.
Change:
to:
For future reference never make assumptions - use a debugger or other tools to verify what the problem is. You might also want to consider reading an introductory book on Objective-C.
问题是 iOS 的级别较低,大概是您所使用的级别,因此 == 实际上是比较地址,而不是字符串。你想要的就是这个。
希望这有帮助。
The problem is iOS is lower level them presumably what you're use to so the == is actually comparing addresses, not strings. What you want is this.
hope this helps.