-1

我有一个 NSString ,它在记录时给了我一个像这样的答案:

Response: oauth_token_secret=6h8hblp42jfowfy&oauth_token=9tmqsojggieln6z

这两个数字每次都在变化。

有没有办法提取这两个数字并创建两个字符串,每个字符串都有一个?

像:

NSString *key = @"9tmqsojggieln6z";
4

3 回答 3

1
//copy the string in a new string variable
NSMutableString *auth_token = [NSMutableString stringWithString:response];

NSRange match = [auth_token rangeOfString: @"&oauth_token="];
[auth_token deleteCharactersInRange: NSMakeRange(0, match.location+13)];
//auth_token will now have the auth token string

NSMutableString *auth_token_secret = [NSMutableString stringWithString:response];
NSRange range1 = [auth_token_secret rangeOfString:[NSString stringWithFormat:@"&oauth_token=%@", auth_token]];
[auth_token_secret deleteCharactersInRange:range1];
NSRange range2 = [auth_token_secret rangeOfString:@"oauth_token_secret="];
[auth_token_secret deleteCharactersInRange: range2];

//auth_token_secret will have the required secret string.
于 2012-07-23T12:32:36.910 回答
0

我有同样的问题。作为响应,我有时会以字符串形式有时以数字形式获取对象的 ID。然后我为 NSDictionary 写了一个类别,它具有以下方法:

- (NSString *)stringFromStringOrNumberForKey:(NSString *)key
{
id secret = [self objectForKey:key];
if ([secret isKindOfClass:[NSNumber class]]) {
    NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];

    secret = [numberFormatter stringFromNumber:secret];
}

return secret;

}

于 2012-07-23T12:17:23.213 回答
0

我会尝试以下方法:

NSString *_response = @"oauth_token_secret=6h8hblp42jfowfy&oauth_token=9tmqsojggieln6z";
NSMutableDictionary *_dictionary = [[NSMutableDictionary alloc] init];
NSArray *_parameters = [_response componentsSeparatedByString:@"&"];
for (NSString *_oneParameter in _parameters) {
    NSArray *_keyAndValue = [_oneParameter componentsSeparatedByString:@"="];
    [_dictionary setValue:[_keyAndValue lastObject] forKey:[_keyAndValue objectAtIndex:0]];
}

// reading the values
NSLog(@"token_secret : %@", [_dictionary valueForKey:@"oauth_token_secret"]);
NSLog(@"token : %@", [_dictionary valueForKey:@"oauth_token"]);
于 2012-07-23T14:02:45.063 回答