Remove last character of NSString

末鹿安然 提交于 2020-04-07 11:08:07

问题


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?


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



回答2:


Try this:

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



回答3:


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

You can see = ABCDE




回答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.




回答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.




回答6:


Simple and Best Approach

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


来源:https://stackoverflow.com/questions/7641624/remove-last-character-of-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!