在iPhone上分割一个字符串的前缀

时间:2021-02-05 03:40:46

Say I have a string like "123alpha". I can use NSNumber to get the 123 out, but how can I determine the part of the string that NSNumber didn't use?

假设我有一个字符串,比如"123alpha"我可以使用NSNumber来得到123,但是我如何确定NSNumber没有使用的字符串的那一部分呢?

3 个解决方案

#1


3  

You can use NSScanner to both get the value and the rest of the string.

您可以使用NSScanner来获取值和字符串的其余部分。

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.

如果在解析值之后确切地知道还剩下什么是重要的,那么这是比试图修饰字符更好的方法。虽然我现在想不出有什么特别糟糕的输入会让OP在评论中建议的解决方案失败,但它看起来就像一个等待发生的bug。

#2


0  

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"]];

#3


0  

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.

如果它以char *开头(与NSString *相反),您可以使用strtol()获取数字,并在一次调用中发现数字的结尾。

#1


3  

You can use NSScanner to both get the value and the rest of the string.

您可以使用NSScanner来获取值和字符串的其余部分。

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.

如果在解析值之后确切地知道还剩下什么是重要的,那么这是比试图修饰字符更好的方法。虽然我现在想不出有什么特别糟糕的输入会让OP在评论中建议的解决方案失败,但它看起来就像一个等待发生的bug。

#2


0  

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"]];

#3


0  

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.

如果它以char *开头(与NSString *相反),您可以使用strtol()获取数字,并在一次调用中发现数字的结尾。