Reputation: 2155
In Objective-C for iOS, how would I remove the last character of a string using a button action?
Upvotes: 154
Views: 113086
Reputation: 40507
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.
Upvotes: 424
Reputation: 15725
The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex
contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex:
to delete the last character correctly.
Upvotes: 8
Reputation: 243146
If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];
Upvotes: 54
Reputation: 9764
The documentation is your friend, NSString
supports a call substringWithRange
that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString
it is immutable. If you have an NSMutableString
is has a method called deleteCharactersInRange
that can modify the string in place
...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...
Upvotes: 6