Remove last character of NSString

Objective CNsstring

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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];

Solution 2 - Objective C

Try this:

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

Solution 3 - Objective C

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

You can see = ABCDE

Solution 4 - Objective C

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 - Objective C

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.

Solution 6 - Objective C

Simple and Best Approach

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkusView Question on Stackoverflow
Solution 1 - Objective CsidyllView Answer on Stackoverflow
Solution 2 - Objective CMark ByersView Answer on Stackoverflow
Solution 3 - Objective CalpertayfunView Answer on Stackoverflow
Solution 4 - Objective CTahir MehmoodView Answer on Stackoverflow
Solution 5 - Objective CkrischuView Answer on Stackoverflow
Solution 6 - Objective CMayur SardanaView Answer on Stackoverflow