NSScanner 在简单的空白删除上的奇怪行为
我试图用一个空格替换某些文本中的所有多个空格。这应该是一个非常简单的任务,但是由于某种原因它返回的结果与预期不同。我已阅读 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
啊,我明白了!默认情况下,NSScanner 会跳过空格!
结果你只需将
charactersToBeSkipped
设置为nil
:Ah, I figured it out! By default the NSScanner skips whitespace!
Turns out you just have to set
charactersToBeSkipped
tonil
: