我想为我的计算器应用实现删除键。我的伪代码是:
foo = length of current number
bar = length of current number-1
current number = current number with character at index (foo-bar) removed
为了在 objective-c 中做到这一点,我尝试使用 NSRange 函数以及 StringbyappendingString 方法来实现:
- (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
}
brainlog 的输出(即 le 和 len 的长度)是:
Len is -1.99164 Le is -1.99164
很难看到,但这是我使用 iOS 模拟器输入到计算器的数字的图像:
我已经尝试更改 le 的值(即使它的显示长度为 -3 或 -5 等)并且 le 和 len 仍然相同。
我也试过引用 len 来制作 le:
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;
但是两者的值还是一样的。如何使用 NSRange 删除显示的最后一个字符?
编辑:使用 Dustin 的修复程序,我现在将一个相当冗长的函数减少为 6 行代码:
-(IBAction)DelPressed{
if ([self.display.text length] >=2)
{
self.display.text = [self.display.text substringToIndes:[self.display.text length] -1];
}
}
最佳答案
改用substring
;如果您只想删除最后一个字符,那就更好了。
更具体地说,substringToIndex(/*length-1*/)
检查 this reference out 如果你需要用字符串做其他事情
关于iphone - 为什么我的 NSRange 总是 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11567049/