2013-02-02 85 views
0

我是新來的目標C和substringToIndex有一個奇怪的問題。ObjectiveC和substringToIndex。問題點

背景: 該代碼是從計算器的顯示中刪除最後一個字符的功能的一部分。我需要能夠標誌時,點被刪除

我的代碼是:

NSString *currentDisplay = self.display.text; 
NSString *lastChar = [currentDisplay substringToIndex: 1]; 
NSLog(@"lastChar -->%@<--",lastChar); 

的問題是: 可變currentDisplay是一個數值,例如「123.45」。當。。。的時候 」。」 (點)是要刪除的字符,所以變量lastChar應該是「。」,日誌顯示一個隨機數,通常是最後一個被刪除的字符。

任何想法我做錯了什麼?

非常感謝, 亞歷克斯

+1

你是子串,而不是刪除字符。所以「最後刪除的字符」是沒有意義的。 (你應該調用變量「firstChar」,而不是「lastChar」,因爲你得到了字符串中的第一個字符。) –

+0

聖潔的廢話我指着第一個字符。我不應該在週末工作。謝謝 – alexgrimaldi

+0

刪除發生在同一個函數 – alexgrimaldi

回答

2

如果你要告訴我們,如果最後一個字符是一個 「點」,使用

if ([currentDisplay characterAtIndex:currentDisplay.length - 1] == '.') .... 
+0

+1後面會更好! (因爲subtringToIndex爲你創建了一個新的字符串對象,而這不) –

+0

這幾乎是我最後的結果。非常感謝 – alexgrimaldi

1

這會幫助你:

BOOL flagIfDotIsDeleted = NO; 
unichar leftmostChar = [currentDisplay characterAtIndex: currentDisplay.length - 1]; 
if (leftmostChar == '.') 
{ 
    flagIfDotIsDeleted = YES; 
    currentDisplay = [currentDisplay substringToIndex: currentDisplay.length - 2]; 
} 
1

這是更簡單,如果你想知道最後一個字符是否是點...

if([currentDisplay hasSuffix:@"."])