如何使用 NSScanner 扫描字符串

发布于 2024-12-12 12:45:43 字数 324 浏览 2 评论 0原文

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

#chat :hi there

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

我已经尝试过

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

但是newarg 仅包含#chat。如何实现这一目标?

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

I've tried

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

But newarg contains only #chat. How this can be achieved?

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

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

发布评论

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

评论(2

无声无音无过去 2024-12-19 12:45:44

示例字符串:

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

代码:

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);

}

输出:

世界你好,
你好吗?

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?

勿挽旧人 2024-12-19 12:45:44

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

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.

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