NSScanner等号后扫描

时间:2012-08-28 18:04:37

标签: xcode nsscanner

oauth_token=requestkey&oauth_token_secret=requestsecret

如何使用NSScanner获取“requestkey”和“requestsecret”。我似乎无法实现它。

NSScanner* scanner = [NSScanner scannerWithString:string];
NSString *oauth_token = @"oauth_token=";
NSString *oauth_token_secret = @"oauth_token_secret=";
[scanner setCharactersToBeSkipped:nil];

NSString *token;
NSString *key;


while (![scanner isAtEnd]) {
    [scanner scanString:oauth_token intoString:NULL];
    [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"&"] intoString:&token];
    [scanner scanUpToString:oauth_token_secret intoString:NULL];
    [scanner scanUpToString:oauth_token intoString:&key];

    NSLog(@"token%@", token);
    NSLog(@"key %@", key);

//token requestkey
//key oauth_token_secret=requestsecret

}

我似乎无法弄清楚为什么它是空的。谢谢!

1 个答案:

答案 0 :(得分:1)

没有什么是空的。所以我不能说出来。

如果您只是逐行遵循代码的逻辑,那么这实际上是一个非常直接的错误。例如:

[scanner scanString:oauth_token intoString:nil];
// The cursor is now just after the equals sign.
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"&"] intoString:&token];
// This leaves the cursor just BEFORE the &.
[scanner scanUpToString:oauth_token_secret intoString:nil];
// This leaves the cursor just BEFORE the "oauth_token_secret="
[scanner scanUpToString:oauth_token intoString:&key];
// This scans effectively the rest of the string into &key which is in fact
// "oauth_token_secret=requestsecret"

解决此问题的最简单方法是使用scanString:intoString:方法将光标前进到oauth_token_secret的末尾。

[scanner scanString:oauth_token intoString:nil];
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"&"] intoString:&token];
[scanner scanUpToString:oauth_token_secret intoString:nil];
// This leaves the cursor just BEFORE the "oauth_token_secret="

// **FIX HERE**
[scanner scanString:oauth_token_secret intoString:nil];
// The cursor is now AFTER oauth_token_secret.

[scanner scanUpToString:oauth_token intoString:&key];

日志输出现在显示有用的字符串。

token:requestkey
key  :requestsecret

但是,正如H2CO3在评论部分中所说,componentsSeparatedByString:更适合此用例。

相关问题