Objective-C – Remove last character from string

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)];

*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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)