目标C - 从字符串中删除最后一个字符 [英] Objective C - Remove last character from string
问题描述
在Objective C中,如何使用按钮操作删除字符串的最后一个字符。
In Objective C for the iPhone, 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.
这篇关于目标C - 从字符串中删除最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!