Objective-C-从字符串中删除最后一个字符 [英] Objective-C - Remove last character from string
问题描述
在iOS版Objective-C中,如何使用按钮操作删除字符串的最后一个字符?
In Objective-C for iOS, how would I remove the last character of a string using a button action?
推荐答案
在您的控制器类中,创建一个操作方法,您可以将该按钮连接到Interface Builder中.在该方法内,您可以像这样修剪字符串:
In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:
if ([string length] > 0) {
string = [string substringToIndex:[string length] - 1];
} else {
//no characters to delete... attempting to do so will result in a crash
}
如果您只想用一种精美的方式在一行代码中完成此操作,则可以将其编写为:
If you want a fancy way of doing this in just one line of code you could write it as:
string = [string substringToIndex:string.length-(string.length>0)];
*花式单行代码段的说明:
如果有要删除的字符(即字符串的长度大于0)
(string.length>0)
返回1
从而使代码返回:
string = [string substringToIndex:string.length-1];
如果没有要删除的字符(即字符串的长度不大于0)
(string.length>0)
返回0
从而使代码返回:
string = [string substringToIndex:string.length-0];
这可以防止崩溃.
*Explanation of fancy one-line code snippet:
If there is a character to delete (i.e. the length of the string is greater than 0)
(string.length>0)
returns 1
thus making the code return:
string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
(string.length>0)
returns 0
thus making the code return:
string = [string substringToIndex:string.length-0];
Which prevents crashes.
这篇关于Objective-C-从字符串中删除最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!