NSScanner 在简单的空白删除上的奇怪行为

发布于 2024-09-01 14:32:45 字数 1071 浏览 3 评论 0原文

我试图用一个空格替换某些文本中的所有多个空格。这应该是一个非常简单的任务,但是由于某种原因它返回的结果与预期不同。我已阅读 NSScanner 上的文档,它似乎无法正常工作!

NSScanner *scanner = [[NSScanner alloc] initWithString:@"This    is   a test of NSScanner   !"];
NSMutableString *result = [[NSMutableString alloc] init];
NSString *temp;
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
while (![scanner isAtEnd]) {

    // Scan upto and stop before any whitespace
    [scanner scanUpToCharactersFromSet:whitespace intoString:&temp];

    // Add all non whotespace characters to string
    [result appendString:temp];

    // Scan past all whitespace and replace with a single space
    if ([scanner scanCharactersFromSet:whitespace intoString:NULL]) {
        [result appendString:@" "];
    }

}

但由于某种原因,结果是 @"ThisisatestofNSScanner!" 而不是 @"This is a test of NSScanner!"

如果您仔细阅读注释以及每一行应该实现的目标,那么看起来很简单!? scanUpToCharactersFromSet 应该在遇到空格时停止扫描器。然后,scanCharactersFromSet 应该让扫描器从空白字符一直到非空白字符。然后循环继续到结束。

我错过了什么或不明白什么?

I'm trying to replace all multiple whitespace in some text with a single space. This should be a very simple task, however for some reason it's returning a different result than expected. I've read the docs on the NSScanner and it seems like it's not working properly!

NSScanner *scanner = [[NSScanner alloc] initWithString:@"This    is   a test of NSScanner   !"];
NSMutableString *result = [[NSMutableString alloc] init];
NSString *temp;
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
while (![scanner isAtEnd]) {

    // Scan upto and stop before any whitespace
    [scanner scanUpToCharactersFromSet:whitespace intoString:&temp];

    // Add all non whotespace characters to string
    [result appendString:temp];

    // Scan past all whitespace and replace with a single space
    if ([scanner scanCharactersFromSet:whitespace intoString:NULL]) {
        [result appendString:@" "];
    }

}

But for some reason the result is @"ThisisatestofNSScanner!" instead of @"This is a test of NSScanner !".

If you read through the comments and what each line should achieve it seems simple enough!? scanUpToCharactersFromSet should stop the scanner just as it encounters whitespace. scanCharactersFromSet should then progress the scanner past the whitespace up to the non-whitespace characters. And then the loop continues to the end.

What am I missing or not understanding?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

惜醉颜 2024-09-08 14:32:45

啊,我明白了!默认情况下,NSScanner 会跳过空格!

结果你只需将 charactersToBeSkipped 设置为 nil

[scanner setCharactersToBeSkipped:nil];

Ah, I figured it out! By default the NSScanner skips whitespace!

Turns out you just have to set charactersToBeSkipped to nil:

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