Can someone help me to extract int timestamp value from this string "/Date(1242597600000)/" in Objective C
I would like to get 1242597600000.
Thx
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];
There's more than one way to do it. Here's a suggestion using an 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.
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString* digitString = [timestampString stringByTrimmingCharactersInSet:nonDigits];
return [digitString longValue];
Related
I need to parse a string like [abc]000, and what I want to get is an array containing abc and 000. Is there an easy way to do it?
I'm using code like this:
NSString *sampleString = #"[abc]000";
NSArray *sampleParts = [sampleString componentsSeparatedByString:#"]"];
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:#"["] lastObject];
NSString *lastPart = [sampleParts lastObject];
But it's inefficient and didn't check whether the string is in a format like [**]**.
For this simple pattern, can just parse yourself like:
NSString *s = #"[abc]000";
NSString *firstPart = nil;
NSString *lastPart = nil;
if ([s characterAtIndex: 0] == '[') {
NSUInteger i = [s rangeOfString:#"]"].location;
if (i != NSNotFound) {
firstPart = [s substringWithRange:NSMakeRange(1, i - 1)];
lastPart = [s substringFromIndex:i + 1];
}
}
Or you could learn to use the NSScanner class.
As always, there are lots of ways to do this.
OPTION 1
If these are fixed length strings (each part is always three characters) then you can simply get the substrings directly:
NSString *sampleString = #"[abc]000";
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)];
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
OPTION 1 (shortened)
NSArray *parts = #[ [sampleString substringWithRange:NSMakeRange(1, 3)],
[sampleString substringWithRange:NSMakeRange(5, 3)] ];
NSLog(#"%#", parts);
OPTION 2
If they aren't always three characters, then you can use NSScanner:
NSString *sampleString = #"[abc]000";
NSScanner *scanner = [NSScanner scannerWithString:sampleString];
// Skip the first character if we know that it will always start with the '['.
// If we can not make this assumption, then we would scan for the bracket instead.
scanner.scanLocation = 1;
NSString *left, *right;
// Save the characters until the right bracket into a string which we store in left.
[scanner scanUpToString:#"]" intoString:&left];
// Skip the right bracket
scanner.scanLocation++;
// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist...
[scanner scanUpToString:#"\0" intoString:&right];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
RESULTS (for all options)
2013-05-10 00:25:02.031 Testing App[41906:11f03] (
abc,
000
)
NOTE
All of these assume well-formed strings, so you should include your own error checking.
try like this ,
NSString *sampleString = #"[abc]000";
NSString *pNRegex = #"\\[[a-z]{3}\\][0-9]{3}";
NSPredicate *PNTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pNRegex];
BOOL check=[PNTest evaluateWithObject:sampleString ];
NSLog(#"success:%i",check);
if success comes as 1 then you can perform the action for separating string into array.
I have a NSArray containing NSStrings with emoji codes in the following format:
0x1F463
How can I now convert them into a NSString with the correct format?
With this method I am able to generate an "Emoji"-NSString:
NSString *emoji = [NSString stringWithFormat:#"\U0001F463"];
But this is only possible with constant NSStrings. How can I convert the whole NSArray?
Not my best work, but it appears to work:
for (NSString *string in array)
{
#autoreleasepool {
NSScanner *scanner = [NSScanner scannerWithString:string];
unsigned int val = 0;
(void) [scanner scanHexInt:&val];
NSString *newString = [[NSString alloc] initWithBytes:&val length:sizeof(val) encoding:NSUTF32LittleEndianStringEncoding];
NSLog(#"%#", newString);
[newString release]; // don't use if you're using ARC
}
}
Using an array of four of your sample value, I get four pairs of bare feet.
You can do it like this:
NSString *str = #"0001F463";
// Convert the string representation to an integer
NSScanner *hexScan = [NSScanner scannerWithString:str];
unsigned int hexNum;
[hexScan scanHexInt:&hexNum];
// Make a 32-bit character from the int
UTF32Char inputChar = hexNum;
// Make a string from the character
NSString *res = [[NSString alloc] initWithBytes:&inputChar length:4 encoding:NSUTF32LittleEndianStringEncoding];
// Print the result
NSLog(#"%#", res);
i need to know how meny image's i have from the file name exp:
i have images call:
first file:
Splash_10001.jpg
last file:
Splash_10098.jpg
and i want to inset then to array..
for(int i = 1; i <= IMAGE_COUNT; i++)
{
UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:#"%#%04d.%#",self.firstImageName,i,self.imageType]];
NSLog(#"%d",i);
[imgArray addObject:image];
}
i want to replace IMAGE_COUNT with number 98 but i need to get the numbre from the string the user send me : Splash_10098.jpg
i need to Separate the Splash_10098.jpg into: nsstring:Splash_1 int:0098 nsstring:jpg
10x all!
It depends what input are of the string is granted. In the following I would search for the dot and go backwards to the maximum of digits.
By the way I could only recommend to use the multi lingual NumberFormatter instead of relying on the default conversion.
NSString * input = #"Splash_19001.jpg";
NSRange r = [input rangeOfString:#"."];
if(r.location>4){
NSString * numberPart = [input substringWithRange: NSMakeRange(r.location-4,4)];
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * number = [nf numberFromString:numberPart];
int val = [number intValue];
NSLog(#"intValue=%d",val);
}
I think this is what you're looking for
NSString *stringUserSendsYou = #"Splash_10098.jpg";
int IMAGE_COUNT = [[[stringUserSendsYou stringByReplacingOccurrencesOfString:#"Splash_1" withString:#""] stringByReplacingOccurrencesOfString:#".jpg" withString:#""] integerValue];
If the number length is fixed in the suffix, it would make sense to use a substring instead of trying to remove the prefix. Strip the extension and grab the last x characters, convert those into an int with either intValue or the NSNumberFormatter suggested by iOS, although that might be unnecessary if you are sure of the format of the string.
NSString *userProvidedString = #"Splash_10001.jpg";
NSString *numberString = [userProvidedString stringByDeletingPathExtension];
NSUInteger length = [numberString length];
NSInteger numberLength = 4;
if (length < numberLength)
{
NSLog(#"Error in the string");
return;
}
numberString = [numberString substringWithRange: NSMakeRange(length - 4, 4)];
NSInteger integer = [numberString integerValue];
// Do whatever you want with the integer.
Using Regex(NSRegularExpression in iOS), this can be done very easily,
Check this out,
NSError *error = NULL;
NSString *originalString = #"Splash_10098.jpg";
NSString *regexString = #"([^\?]*_[0-9])([0-9]*)(.)([a-z]*)";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:originalString options:NSRegularExpressionCaseInsensitive range:NSMakeRange(0, [originalString length])];
NSLog(#"FileName: %#", [originalString substringWithRange:[match rangeAtIndex:1]]);
NSLog(#"Total Count: %#", [originalString substringWithRange:[match rangeAtIndex:2]]);
NSLog(#"File type: %#", [originalString substringWithRange:[match rangeAtIndex:4]]);
Result:
FileName: Splash_1
Total Count: 0098
File type: jpg
I have an NSString which when logged gives me an answer like this one:
Response: oauth_token_secret=6h8hblp42jfowfy&oauth_token=9tmqsojggieln6z
The two numbers change every single time.
Is there a way to extract the two numbers and create two strings with one of each??
Like:
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.
I had the same problem. As response I get the ids of objects sometimes as string sometimes as numbers. Then I wrote a category for NSDictionary which has the following method:
- (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;
}
I would try the following:
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"]);
If I want to get a value from the NSString #"value:hello World:value", what should I use?
The return value I want is #"hello World".
Option 1:
NSString *haystack = #"value:hello World:value";
NSString *haystackPrefix = #"value:";
NSString *haystackSuffix = #":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(#"needle: %#", needle); // -> "hello World"
Option 2:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];
This one might be a bit over the top for your rather trivial case though.
Option 3:
NSString *needle = [haystack componentsSeparatedByString:#":"][1];
This one creates three temporary strings and an array while splitting.
All snippets assume that what's searched for is actually contained in the string.
Here's a slightly less complicated answer:
NSString *myString = #"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];
See also substringWithRange and substringFromIndex
Here's a simple function that lets you do what you are looking for:
- (NSString *)getSubstring:(NSString *)value betweenString:(NSString *)separator
{
NSRange firstInstance = [value rangeOfString:separator];
NSRange secondInstance = [[value substringFromIndex:firstInstance.location + firstInstance.length] rangeOfString:separator];
NSRange finalRange = NSMakeRange(firstInstance.location + separator.length, secondInstance.location);
return [value substringWithRange:finalRange];
}
Usage:
NSString *myName = [self getSubstring:#"This is my :name:, woo!!" betweenString:#":"];
Use this also
NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];
Note - Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);
Here is a little combination of #Regexident Option 1 and #Garett answers, to get a powerful string cutter between a prefix and suffix, with MORE...ANDMORE words on it.
NSString *haystack = #"MOREvalue:hello World:valueANDMORE";
NSString *prefix = #"value:";
NSString *suffix = #":value";
NSRange prefixRange = [haystack rangeOfString:prefix];
NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix];
NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(#"needle: %#", needle);