2011-01-14 29 views
0

我正在努力獲得一個簡單的計算器,作爲我學習Object-C和iOS開發的一部分冒險工作。如何找到'。'在Object-C中的字符串對象-I

在使用NSString的Object-C中,如何查找字符串中的句點?

基於評論,這是我到目前爲止。

NSString * tmp = [display text]; 

NSLog(@"%@", tmp); // Shows the number on the display correctly 

int x = [tmp rangeOfString:@"."].location; 

NSLog(@"%i", x); // Shows some random signed number 

if (x < 0) { 
    [display setText:[[display text] stringByAppendingFormat:@"."]]; 
} 

它仍然沒有工作:(

回答

0

NSRange是一個直線上升的結構...

typedef struct _NSRange { 
     NSUInteger location; 
     NSUInteger length; 
} NSRange; 

int x = [@"hello.there.ok" rangeOfString:@"."].location; 
printf("x is %d\n",x); 

打印5.

,這裏是一個完整的程序:

int main(int argc, char *argv[]) 
{ 
    NSString *ht = @"This is a string"; 
    int r1 = [ht rangeOfString:@"is"].location; 
    int r2 = [ht rangeOfString:@"is a"].location; 
    int r3 = [ht rangeOfString:@"isnt"].location; 
    NSLog(@"r1=%d, r2=%d, r3=%d, that's all\n",r1,r2,r3); 
} 

打印:

Program loaded. 
run 
[Switching to process 21098] 
Running… 
2011-01-14 20:45:25.192 DELETEME[21098:a0b] r1=2, r2=5, r3=-1, that's all 

在XCode,Mac OS中運行此應該是直截了當!

+0

//獲取titleLabel文本中的字符串 NSString * digit = [[sender titleLabel] text]; int x = [digit rangeOfString:@「。」]。location;如果(!x){ //如果不存在小數,則執行此 } – nzaccardi 2011-01-14 05:31:00