Reputation: 3678
I have a NSString *text = @"randomtext12345"
The text string will always begins with 'string' (unknown length) and followed by 'number' (integer type).
There is no 'seperator' in between the text, how do I detect which is string and integer? in order to extract/seperate/seperate out the text to become
NSString *key = @"randomtext";
NSInteger value = 12345;
Upvotes: 2
Views: 2145
Reputation: 25740
This assumes that all numeric values are grouped together at the end (i.e. there are no numbers in the "randomtext" portion). Also, I have not included error checking to make sure that the input string (text
) is in the correct format. (i.e. there must be an alpha portion followed by a numeric portion):
NSString *text = @"randomtext12345";
NSRange beginningOfNumber = [text rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
if (beginningOfNumber.location == NSNotFound)
{
return;
}
NSString *key = [text substringToIndex:beginningOfNumber.location];
NSString *stringValue = [text substringFromIndex:beginningOfNumber.location];
NSInteger value = [stringValue integerValue];
// Output: 2012-07-29 14:08:56.504 Testing App[46439:fb03] key: randomtext, value: 12345
Upvotes: 5
Reputation: 378
You need to add a separator string between the string and number.
"~" in this example.
NSInteger is not an object, so don't use the "*".
NSString *test = @"randomtext~12345";
NSArray *testItems = [test componentsSeparatedByString:@"~"];
NSString *key = [testItems objectAtIndex:0];
NSInteger value = [[testItems objectAtIndex:1] intValue];
NSLog(@"test key=%@ and value=%ld", key, value);
Upvotes: 1