objective-c 如何在Objective C中解析字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/938586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse strings in Objective C
提问by Mladen
Can someone help me to extract int timestamp value from this string "/Date(1242597600000)/" in Objective C
有人可以帮我从 Objective C 中的字符串 "/Date(1242597600000)/" 中提取 int 时间戳值吗
I would like to get 1242597600000.
我想得到 1242597600000。
Thx
谢谢
回答by Tom Jefferys
One simple method:
一种简单的方法:
NSString *timestampString = @"\/Date(1242597600000)\/";
NSArray *components = [timestampString componentsSeparatedByString:@"("];
NSString *afterOpenBracket = [components objectAtIndex:1];
components = [afterOpenBracket componentsSeparatedByString:@")"];
NSString *numberString = [components objectAtIndex:0];
long timeStamp = [numberString longValue];
Alternatively if you know the string will always be the same length and format, you could use:
或者,如果您知道字符串的长度和格式始终相同,则可以使用:
NSString *numberString = [timestampString substringWithRange:NSMakeRange(7,13)];
And another method:
还有一种方法:
NSRange openBracket = [timestampString rangeOfString:@"("];
NSRange closeBracket = [timestampString rangeOfString:@")"];
NSRange numberRange = NSMakeRange(openBracket.location + 1, closeBracket.location - openBracket.location - 1);
NSString *numberString = [timestampString substringWithRange:numberRange];
回答by Abizern
There's more than one way to do it. Here's a suggestion using an NSScanner;
有不止一种方法可以做到。这是使用 NSScanner 的建议;
NSString *dateString = @"\/Date(1242597600000)\/";
NSScanner *dateScanner = [NSScanner scannerWithString:dateString];
NSInteger timestamp;
if (!([dateScanner scanInteger:×tamp])) {
// scanInteger returns NO if the extraction is unsuccessful
NSLog(@"Unable to extract string");
}
// If no error, then timestamp now contains the extracted numbers.
回答by Nikolai Ruhe
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString* digitString = [timestampString stringByTrimmingCharactersInSet:nonDigits];
return [digitString longValue];

