2

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; 
4

2 回答 2

5

这假设所有数值在最后被组合在一起(即“随机文本”部分中没有数字)。此外,我没有包括错误检查以确保输入字符串 ( text) 的格式正确。(即必须有一个字母部分后跟一个数字部分):

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
于 2012-07-29T18:10:40.327 回答
1

您需要在字符串和数字之间添加分隔符字符串。
本例中为“~”。
NSInteger 不是对象,所以不要使用“*”。


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);
于 2012-07-29T17:38:31.063 回答