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
2009-07-04 13:22:58
NSMakeRange can sometimes make filling out a range struct look a little more elegant.
dreamlax
2009-07-04 13:40:14
+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
2009-07-04 13:26:19
Your solution has an off by 1 bug. It should be[string substringToIndex:[string length] - 1];
Jim Correia
2009-07-04 14:46:10
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
2009-07-06 12:39:24
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
2009-07-04 13:45:58