views:

3083

answers:

3

In Objective C for the iPhone, how would I remove the last character of a string using a button action.

+2  A: 

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];
...
Harald Scheirich
NSMakeRange can sometimes make filling out a range struct look a little more elegant.
dreamlax
+14  A: 

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];
Marc Charbonneau
That is the better call, missed that.
Harald Scheirich
Your solution has an off by 1 bug. It should be[string substringToIndex:[string length] - 1];
Jim Correia
Does "string" refer to "string.text" or just the string name
Omar
Thanks Jim, it was too early in the morning for arithmetic I guess. :) Omar, string refers to a variable called string that holds the text you want to modify. You can take a look at the documentation for the different ways you can create an NSString object, either from a file on disk or from data in your application.
Marc Charbonneau
A: 

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

[myString replaceCharactersInRange:NSMakeRange([myString length]-1, 1) withString:@""];
Dave DeLong