Splitting a number off prefix of a string on iPhone
Say I have a string like "123alpha". I can use NSNumber to get the 123 out, but how can I determine the pa开发者_开发知识库rt of the string that NSNumber didn't use?
You can use NSScanner
to both get the value and the rest of the string.
NSString *input = @"123alpha";
NSScanner *scanner = [NSScanner scannerWithString:input];
float number;
[scanner scanFloat:&number];
NSString *rest = [input substringFromIndex:[scanner scanLocation]];
If it is important to know exactly what is left after parsing the value this is a better approach than trying to trim characters. While I can't think of any particular bad input at the moment that would fail the solution suggested by the OP in the comment to this answer, it looks like a bug waiting to happen.
if your numbers are always at the beginning or end of a string and you want only the remaining characters, you could trim with a character set.
NSString *alpha = @"123alpha";
NSString *stripped = [alpha stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]];
If its starts out as a char *
(as opposed to an NSString *
), you can use strtol()
to get the number and discover where the number ends in a single call.
精彩评论