Remove last character of NSString
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?
Solution 1:
NSString *newString = [oldString substringToIndex:[oldString length]-1];
Always refer to the documentation:
substringToIndex:
length
To include code relevant to your case:
NSString *str = textField.text;
NSString *truncatedString = [str substringToIndex:[str length]-1];
Solution 2:
Try this:
s = [s substringToIndex:[s length] - 1];
Solution 3:
NSString *string = [NSString stringWithString:@"ABCDEF"];
NSString *newString = [string substringToIndex:[string length]-1];
NSLog(@"%@",newString);
You can see = ABCDE
Solution 4:
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.
Solution 5:
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.