0
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

}

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

4

1 回答 1

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:它更适合这个用例。

于 2012-08-28T19:12:32.600 回答