I want to implement a delete key for my calculator app. My pseudocode for this was:
foo = length of current number
bar = length of current number-1
current number = current number with character at index (foo-bar) removed
To do this in objective-c I have tried to implement this using the NSRange function as well as the StringbyappendingString method:
- (IBAction)DelPressed {
if ([self.display.text length] >=2)
{
int len = [self.display.text length];//Length of entire display
//Add to the brainlong printing out the length of the entire display
self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len];
int le = ([self.display.text length]-1);//Length of entire display - 1
NSString *lestring = [NSString stringWithFormat:@"LE is %g",le];
//Add to the brainlog printing out the length of the display -1
self.brainlog.text = [self.brainlog.text stringByAppendingString:lestring];
NSRange range = NSMakeRange(le, len);//range only includes the last character
self.display.text = [self.display.text stringByReplacingCharactersInRange:range withString:@" "];//Replace the last character with whitespace
}
The output to brainlog (ie the length of both le and len) is:
Len is -1.99164 Le is -1.99164
Hard to see, but here's an image of the number I input to the calculator using the iOS simulator:
I have tried to change the value of le (ie making it the length of the display -3 or -5 etc) and both le and len are still the same.
I have also tried to make le in reference to len:
int len = [self.display.text length];//Length of entire display
//Add to the brainlong printing out the length of the entire display
self.brainlog.text = [NSString stringWithFormat:@"Len is %g",len];
int le = len-1;
But the values of the two are still the same. How can I use NSRange to delete the last character of the display?
Edit: Using Dustin's fix, I now have reduced a rather lengthy function into 6 lines of code:
-(IBAction)DelPressed{
if ([self.display.text length] >=2)
{
self.display.text = [self.display.text substringToIndes:[self.display.text length] -1];
}
}
brainlog
? Maybe I'm missing something, but it seems like the real question here has nothing to do withNSRange
but instead should be about how on earth you're storing the length of a string as an int and ending up with a negative float instead. Have you tried usingNSLog(@"len is %d", len)
to verify the value oflen
? – Frink%d
instead of%g
)? – Frink