74
votes

I've got some trouble 'ere trying to remove the last character of an NSString. I'm kinda newbie in Objective-C and I have no idea how to make this work.

Could you guys light me up?

6
"Could you guys light me up?". The usage you're looking for is "enlighten me". - user244343

6 Answers

200
votes
NSString *newString = [oldString substringToIndex:[oldString length]-1];

Always refer to the documentation:


To include code relevant to your case:

NSString *str = textField.text;
NSString *truncatedString = [str substringToIndex:[str length]-1];
13
votes

Try this:

s = [s substringToIndex:[s length] - 1];
5
votes
NSString *string = [NSString stringWithString:@"ABCDEF"];
NSString *newString = [string substringToIndex:[string length]-1];
NSLog(@"%@",newString);

You can see = ABCDE

4
votes
NSString = *string = @"abcdef";

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

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.

1
votes

This code will just return the last character of the string and not removing it :

NSString *newString = [oldString substringToIndex:[oldString length]-1];

you may use this instead to remove the last character and retain the remaining values of a string :

str = [str substringWithRange:NSMakeRange(0,[str length] - 1)];

and also using substringToIndex to a NSString with 0 length will result to crashes.

you should add validation before doing so, like this :

if ([str length] > 0) {

   str = [str substringToIndex:[s length] - 1];

}

with this, it is safe to use substring method.

NOTE : Apple will reject your application if it is vulnerable to crashes.

0
votes

Simple and Best Approach

[mutableString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];