[ACCEPTED]-Objective-C - Remove last character from string-cocoa-touch

Accepted answer
Score: 423

In your controller class, create an action 13 method you will hook the button up to in 12 Interface Builder. Inside that method you 11 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 10 a fancy way of doing this in just one line 9 of code you could write it as:

string = [string substringToIndex:string.length-(string.length>0)];

*Explanation 8 of fancy one-line code snippet:

If there 7 is a character to delete (i.e. the length 6 of the string is greater than 0)
     (string.length>0) returns 5 1 thus making the code return:
          string = [string substringToIndex:string.length-1];

If 4 there is NOT a character to delete (i.e. the 3 length of the string is NOT greater than 2 0)
     (string.length>0) returns 0 thus making the code 1 return:
          string = [string substringToIndex:string.length-0];
     Which prevents crashes.

Score: 53

If it's an NSMutableString (which I would 2 recommend since you're changing it dynamically), you 1 can use:

[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];
Score: 8

The solutions given here actually do not 8 take into account multi-byte Unicode characters 7 ("composed characters"), and could 6 result in invalid Unicode strings.

In fact, the 5 iOS header file which contains the declaration 4 of substringToIndex contains the following comment:

Hint: Use 3 with rangeOfComposedCharacterSequencesForRange: to 2 avoid breaking up composed characters

See 1 how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.

Score: 6

The documentation is your friend, NSString supports 5 a call substringWithRange that can shorten the string that 4 you have an return the shortened String. You 3 cannot modify an instance of NSString it is immutable. If 2 you have an NSMutableString is has a method called deleteCharactersInRange that 1 can modify the string in place

NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];

More Related questions