Splitting a number with a line prefix on an iPhone

Let's say I have a string like "123alpha". I can use NSNumber to get 123, but how do I determine the portion of a string that NSNumber has not used?

+3
source share
3 answers

You can use NSScannerto 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’s important to know exactly what remains after parsing the value, this is a better approach than trying to trim characters. Although I cannot come up with any specific bad input at that point that could not offer the solution proposed by the OP in the commentary to this, it looks like a pending error will occur.

+2
source

, .

NSString *alpha = @"123alpha";
NSString *stripped = [alpha stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]];
0

If it starts with char *(as opposed to NSString *), you can use strtol()to get the number and find out where the number ends in one call.

0
source

Source: https://habr.com/ru/post/1779217/


All Articles