iOS:如何从缓冲区或字符串中删除空字符?

发布于 2024-11-28 08:51:32 字数 785 浏览 1 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

通知家属抬走 2024-12-05 08:51:32

您对代码不起作用的原因做出了错误的假设。

更改

if (strCut == @"B")

为:

if ([strCut isEqualToString:@"B"])

供将来参考,切勿做出假设 - 使用调试器或其他工具来验证问题所在。您可能还想考虑阅读一本关于 Objective-C 的介绍性书籍。

You're making a bad assumption about why your code is not working.

Change:

if (strCut == @"B")

to:

if ([strCut isEqualToString:@"B"])

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.

定格我的天空 2024-12-05 08:51:32

问题是 iOS 的级别较低,大概是您所使用的级别,因此 == 实际上是比较地址,而不是字符串。你想要的就是这个。

if ([strCut compare:@"B"] == NSOrderedSame) {
   ...
}

希望这有帮助。

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.

if ([strCut compare:@"B"] == NSOrderedSame) {
   ...
}

hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文