xcode 如何使用 NSScanner 从字符串中扫描

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7944607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:16:56  来源:igfitidea点击:

How to use NSScanner to scan from a string

objective-cxcodecocoansstring

提问by pmerino

I have a string which looks like:

我有一个看起来像的字符串:

#chat :hi there

And I'd like to scan all the text from the :to a string, so it ends like hi there

我想扫描所有文本:到一个字符串,所以它的结尾像hi there

I've tried

我试过了

[[NSScanner scannerWithString:argument] scanUpToString:@":" intoString:&newarg];

But newargcontains only #chat. How this can be achieved?

newarg只包含#chat. 如何做到这一点?

回答by Anne

Example String:

示例字符串:

#chat :Hello World,
#chat :How are you doing?

Code:

代码:

NSString *theString =   @"#chat :Hello World,\n"
                         "#chat :How are you doing?";

NSScanner *theScanner = [NSScanner scannerWithString:theString];
NSCharacterSet *seperator = [NSCharacterSet characterSetWithCharactersInString:@":"];
NSCharacterSet *newLine = [NSCharacterSet newlineCharacterSet];
NSString *theText;

while ([theScanner isAtEnd] == NO) {

    [theScanner scanUpToCharactersFromSet:seperator intoString:NULL];
    [theScanner setScanLocation: [theScanner scanLocation]+1];
    [theScanner scanUpToCharactersFromSet:newLine intoString:&theText];

    NSLog(@"%@",theText);

}

Output:

输出:

Hello World,
How are you doing?

世界你好,
你好吗?

回答by samuelb

Consider using an if statement to iterate through the scan. You've always told the computer to scan everything until the character ":", but it sounds like you actually want to scan everything AFTER the ":" character. Anne's answer provides an excellent example of such.

考虑使用 if 语句遍历扫描。您总是告诉计算机扫描所有内容,直到字符“:”,但听起来您实际上想扫描“:”字符之后的所有内容。安妮的回答提供了一个很好的例子。