此方法:
- (BOOL)checkForDigits {
NSString *editableExpression = self.expression.text;
for (int i = 0; i < editableExpression.length; i++){
char charAtPosition = [editableExpression characterAtIndex:i];
for (int c = 0; c < 10; c++ ){
char digitAtPosition = digits[c];
if (charAtPosition == digitAtPosition){
return TRUE;
}
else {
return FALSE;
}
}
}
}
总是似乎返回FALSE,我无法弄清楚原因。我会使用isnan方法,但我尝试了它并没有用,所以我只做了我自己的isnan(真的与isnan相反)。数字数组只是
char digits[10] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
答案 0 :(得分:2)
使用此:
- (BOOL)checkForDigits {
char digits[10] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
BOOL result;
NSString *editableExpression = @"dsjkdjk12lkv";
for (int i = 0; i < editableExpression.length; i++){
char charAtPosition = [editableExpression characterAtIndex:i];
for (int c = 0; c < 10; c++ ){
char digitAtPosition = digits[c];
if (charAtPosition == digitAtPosition){
NSLog(@"true");
return TRUE;
}
else {
result = FALSE;
}
}
}
return result;
}
实际上它只在第一个循环中返回false。所以循环只运行了一个周期。
答案 1 :(得分:0)
答案 2 :(得分:0)
可能是使用NSScanner的更好方法吗?
NSScanner *scanner = [NSScanner scannerWithString:string];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
[scanner scanCharactersFromSet:numbers intoString:&obj1String];
obj1Num = [NSNumber numberWithInt:[obj1String integerValue]];
if(obj1String) {
} else {
}
答案 3 :(得分:0)
您的editableExpression
不是从数字开始的。
NSString *editableExpression =@"A1" // return false
NSString *editableExpression =@"1A" // return True
//This will return TRUE if string contain digit
- (BOOL)checkForDigits {
NSString *editableExpression = @"1a1";
for (int i = 0; i < editableExpression.length; i++){
char charAtPosition = [editableExpression characterAtIndex:i];
for (int c = 0; c < 10; c++ ){
char digitAtPosition = digits[c];
if (charAtPosition == digitAtPosition){
return TRUE;
}
}
}
return FALSE;
}
答案 4 :(得分:0)
试试这个:
NSRange match = [string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet] options:0 range:NSMakeRange(0, string.length)];
if (match.location == NSNotFound) return NO;
else return YES;
答案 5 :(得分:0)
试试这个:
BOOL containsDigits(NSString *s) {
NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:@"123456789"];
NSRange range = [s rangeOfCharacterFromSet:cs];
return range.location != NSNotFound;
}
答案 6 :(得分:0)
通过以下方式修改
- (BOOL)checkForDigits {
NSString *editableExpression = self.expression.text;
BOOL isDigit = FALSE;
for (int i = 0; i < editableExpression.length; i++){
char charAtPosition = [editableExpression characterAtIndex:i];
for (int c = 0; c < 10; c++ ){
char digitAtPosition = digits[c];
if (charAtPosition == digitAtPosition){
return TRUE;
}
}
}
return FALSE;
}