Objective
In the development of the project, the encounter needs may be let us enter only a paragraph of pure numbers, this time we have to filter the string to judge, do not conform to the pure number of prompts to operate, in order to achieve the best interactive effect can meet the needs.
Here are a few ways to determine whether a string is a pure number
The first way is to use Nsscanner:
1. Shaping Judgment
-(BOOL) Ispureint: (NSString *) string{
nsscanner* scan = [Nsscanner scannerwithstring:string];
int Val;
return [scan scanint:&val] && [scan isatend];
}
2. Floating-point shape judgment:
-(BOOL) Ispurefloat: (NSString *) string{
nsscanner* scan = [Nsscanner scannerwithstring:string];
float Val;
return [scan scanfloat:&val] && [scan isatend];
}
The second way is to use circular judgment
-(BOOL) Ispurenumandcharacters: (NSString *) text
{for
(int i = 0; i < [text length]; ++i) {
int a = [text ch ARACTERATINDEX:I];
if ([self isnum:a]) {
continue;
} else {return
NO;
}
}
Return YES
}
Or the common way in C language.
-(BOOL) Isallnum: (NSString *) string{
Unichar C;
for (int i=0; i<string.length; i++) {
c=[string characteratindex:i];
if (!isdigit (c)) {return
NO;
}
}
Return YES
}
The third way is to use the trimming method of NSString
-(BOOL) Ispurenumandcharacters: (NSString *) string
{
string = [string stringbytrimmingcharactersinset;[ Nscharacterset Decimaldigitcharacterset]];
if (String.Length > 0)
{return
NO;
}
Return YES
}
Summarize
The above is a summary of three functions that can help you to determine whether a string is a number. iOS does not directly determine whether the number of methods, so you can only add methods to achieve. I hope this article summed up several ways to help everyone, if you have questions can be exchanged message.