从NSString中提取数字
我有一个NSString,当登录时给我这样一个答案:
Response: oauth_token_secret=6h8hblp42jfowfy&oauth_token=9tmqsojggieln6z
这两个数字每次都会改变。
有没有办法提取这两个数字并创建两个字符串中的每一个?
喜欢:
NSString *key = @"9tmqsojggieln6z";
//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.
我有同样的问题。 作为回应,我有时将对象的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;
}
我会尝试以下方法:
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"]);
链接地址: http://www.djcxy.com/p/85231.html
上一篇: Extracting number from NSString
下一篇: Is there a way to count the number of lines of a NSString ?